I cannot get understanding code to work? I dont know why? Is it even possible?
I want always to call a default class and there methods. But actually depending on the parameter givven. I want to load methods from that specifiec customer?
<?php
#System Defaults
namespace DefaultNameSpace;
class defaultClass{
private $property;
public function __construct($cusotmer)
{
if (isset($cusotmer)){
$namespace = '\Customer' . $cusotmer .'Namespace\defaultClass';
# create new dynamic object
return new $namespace();
} else {
return $this;
}
}
public function printInvoice(){
echo 'Default Print';
}
public function createInvoice($invoice){}
}
#Customer One defaults
namespace CustomerOneNamespace;
class defaultClass extends \DefaultNameSpace\defaultClass {
private $property;
public function __construct()
{
return $this;
}
public function printInvoice(){
echo 'Customer One';
}
public function createInvoice ($invoice){
echo 'Create invoice Customer One '.$invoice;
}
}
# Customer Two Defaults
namespace CustomerTwoNamespace;
class defaultClass extends \DefaultNameSpace\defaultClass {
private $property;
public function __construct()
{
return $this;
}
public function printInvoice(){
echo 'Customer Two';
}
}
# Call alsways default Class
$test = new \DefaultNameSpace\defaultClass('Two');
$test->printInvoice();
$test->createInvoice('123456');
?>
You can’t create an object of descendatnt class when calling ancestor class’ constructor, so this code will not work as you want.
To achieve what you want you could use
Factorypattern. Simplified (and very primitive) example:Note that you are completely responsible for returning from
factoryMethodobjects that implement required interface, as PHP do not support return type hinting (as far as I know).