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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测