Strongly Typed PHP
January 28, 2007 by
This post is closed for comments.
This post is marked as obsolete.
This post has officially been retired, an updated post (post PHP 7.x)
can be read over here
Often you'll hear the term "strongly typed" which refers to certain constraints
being enforced regarding the type of a variable. (e.g. inability to compare a string value to an integer value unless you explicitly convert the string value to an integer)
PHP in contrast is a "weakly typed" language which means PHP implicitly converts types when/as needed. (sometimes in a funky manner)
Its also regarded as "dynamically typed" since instead of being required to explicitly declare the type of your variables (which one cant do in PHP, minus type hinting)
types get derived from the value assigned to it (and re-derived when needed)
But what if you want to make your classes strongly typed? (Force whoever
use our class to assign the correct type of values to our class properties)
- surely we can put checks
in our code, but that can get a bit tedious.
Overloading in PHP 5 is a quick solution, one can overload the get and set members
and control whatever variables get assigned and retrieved from your class.
Here is a quick snippet:
public function __get($name)
die("<b>Exception occured: </b>calling property $name which does not exist or set private");
public function __set($name,$value)
$type = $this->enforcetype[$name];
if (isset($type) && $type != "")
$given = gettype($value);
if ($given == $type)
$this->x[$name] = $value;
$exception = ($given != "") ? "<b>Exception occured on $name property:</b>
Type <i>$type</i> expected, type <i>$given</i> was supplied"
: "<b>Exception occured:</b> no type specified for property $name";
else die("<b>Exception occured:</b> property $name not defined<br/>");
In the next snippet we inherit from the top class our "constraining class", we need to create an array, which contains our variable
names and our preset types we want to constraint on.
class test extends StronglyTyped
protected $enforcetype = array("stringy" => "string",
"inty" => "integer",
"booly" => "bool");
Once we instantiate the class, and try to assign an integer value for example, to the stringy member, we
get an exception, since we specified that we only accept string types for that member. If we try to assign to
undefined members we get an exception as well, all much like we see in languages like C#.
$a = new test();
//$a->inty = "10"; // Exception occured on inty property: Type integer expected, type string was supplied
//$a->stringy = 1; // Exception occured on stringy property: Type string expected, type integer was supplied
//$a->booly = "test"; // Exception occured on booly property: Type bool expected, type string was supplied
Apparently as of PHP 5.3, you're not allowed to set the visibility of magic methods to private/protected, only as public - I altered the snippets to reflect this change.