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.
$test = new \DefaultNameSpace\defaultClass('Two');
To achieve what you want you could use Factory
pattern. Simplified (and very primitive) example:
function factoryMethod($type){
$result = null;
switch($type){
case 1:
$result = new Class1();
break;
case 2:
$result = new Class2();
break;
default:
$result = new ClassDefault();
break;
}
return $result;
}
$obj = factoryMethod(2);
$obj->printInvoice();
Note that you are completely responsible for returning from factoryMethod
objects that implement required interface, as PHP do not support return type hinting (as far as I know).
精彩评论