方法重载和类继承

时间:2011-08-16 07:47:01

标签: php class namespaces overloading

我无法理解代码工作?我不知道为什么?它甚至可能吗?

我希望始终调用默认类和方法。但实际上取决于参数givven。我想从该特定客户加载方法?

<?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');

?>

1 个答案:

答案 0 :(得分:3)

在调用祖先类的构造函数时,不能创建descendatnt类的对象,因此此代码将无法正常工作。

$test = new \DefaultNameSpace\defaultClass('Two'); 

要实现您的目标,您可以使用Factory pattern。简化(和非常原始)的例子:

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();

请注意,您完全负责从实现所需接口的factoryMethod对象返回,因为PHP不支持返回类型提示(据我所知)。