Strongly Typed PHP
Often you'll hear the term "strongly typed" which refers to certain constraints
being enforced regarding variables.
PHP is a "weakly typed" language which means php doesn't require (nor support it for that matter)
explicit type declaration of variables.
Whatever value one assign to a variable, determines its type and when you assign something else to
it, it changes type according again. (Most uncompiled languages use this technique)
(which can lead to very dodge code)
But what if you want to make your classes strongly typed? (Force whoever
use your class to assign the correct values to your 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:
<?php
class StronglyTyped
{
private $x;
public function __get($name)
{
if (!isset($this->enforcetype[$name]))
{
die("<b>Exception occured: </b>calling property $name which does not exist or set private");
}
return $this->x[$name];
}
public function __set($name,$value)
{
$type = $this->enforcetype[$name];
if (isset($type) && $type != "")
{
$given = gettype($value);
if ($given == $type)
$this->x[$name] = $value;
else
{
$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";
die($exception);
}
}
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
Update 2010-12-16
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.
Posted by - Christoff Truter
Date - 2007-01-28 12:00:00
Comments
Post comment