dongyanju0945 2012-08-21 02:28
浏览 81
已采纳

我可以从基础工厂方法调用私有子构造函数吗?

I'd like to implement the following using a private constructor.

The problem is that get_class() returns ParentBase; eventhough; get_called_class() returns ChildClass.

How can I have __construct() be called from the calling class context instead of the base class context?

There will be many child classes, so I only want one shared factory method, and I also want to make sure a child cannot be extended (so that it cannot be created with the new keyword).

Seems like there should be a way of making ChildClass::createObject() work with a private ChildClass constructor and a public ParentBase factory method.

<?php
class ParentBase 
{
    public static function createObject() 
    {
        echo get_class() . "<br/>";        // prints ParentBase
        echo get_called_class() . "<br/>"; // prints ChildClass
        return new static();
    }
}

class ChildClass extends ParentBase
{
    private $greeting = "bye";

    private function __construct()
    {
        $this->greeting = "hi";
    }

    public function greet()
    {
        echo $this->greeting;
    }
}

$child = ChildClass::createObject();
$child->greet();

The output from the above is:

ParentBase
ChildClass
Fatal error: Call to private ChildClass::__construct() from context 'ParentBase' 

Protected contstructor works: http://codepad.viper-7.com/sCgJwA

Private constructor doesn't: http://codepad.viper-7.com/YBs7Iz

  • 写回答

3条回答 默认 最新

  • dongxu0690 2012-08-21 02:40
    关注

    That is an expected behavior createObject(); is a function of ParentBase, So it will return ParentBase from get_class() but, it was called from ChildClass So, it will return ChildClass from get_called_class().

    And about the constructor, since the constructor is assigned as private, you restrict the object creation from within the class only. By making it protected, now Parent Class can create the object of ChildClass

    Probable solution would be to override, the createObject() class in the ChildClass itself.

    class ChildClass extends ParentBase
    {
        public static function createObject() 
        {
            echo get_class() . "<br/>";
            echo get_called_class() . "<br/>";
            return new static();
        }
    }
    

    Or, you could make the constructor protected, then you will make the constructor accessible to parent classes and restrict any sub classes of child classes making it final, thus making it accessible from parent class only.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog