Since PHP is a loosely typed language, it provides great flexibility in creating variables and objects at runtime without having to specifically declare them first. It is well known that $i=10, $i=”test”, $i = date() will all work without creating any syntax or compile errors.
A lesser used concept is that this feature can be used to create an object at runtime without having to check for the object type at first. Eg.if you have had 3 classes and only one of them had to be created depending on a condition the following would be the sample code:
<?php
error_reporting(E_ALL);
class Generic {
function xprint() {
echo("generic");
}
}
class A extends Generic{
function xprint() {
echo("A");
}
}
class B extends Generic{
function xprint() {
echo ("B");
}
}
class C extends Generic{
function xprint() {
echo("C");
}
}
$test = "B";
if ($test =="B")
$x = new B();
else if ($test == "A"
$x = new A();
else if ($test == "C")
$x = new C();
$x->xprint();
echo("end");
?>
Instead of doing multiple checks and then creating the relevant class, a more efficient way is to pass the classname as a string and then create it directly as shown below:
<?php
error_reporting(E_ALL);
class Generic {
function xprint() {
echo("generic");
}
}
class A extends Generic{
function xprint() {
echo("A");
}
}
class B extends Generic{
function xprint() {
echo ("B");
}
}
class C extends Generic{
function xprint() {
echo("C");
}
}
$test = "B";
$x = new $test();
$x->xprint();
echo("end");
?>
The above code will print “B” since it creates the class B in $x. What about classes where arguments are required in the constructor? Simple call it with the arguments eg. $x = new $test(“arg1″, “arg2″);