【问题标题】:Calling a PHP constructor from its own method从自己的方法调用 PHP 构造函数
【发布时间】:2012-06-11 04:53:40
【问题描述】:

我一直在寻找一种调用类的构造函数的方法,它类似于“parent::_construct”,但用于类本身(类似于“self::_construct”,不过这不起作用)。为什么要这样做?考虑以下(这不起作用,顺便说一句)...

class A {
  var $name;
  function __construct($name) {
    $this->name = $name;
  }
  function getClone($name) {
    $newObj = self::__construct($name);
    return $newObj;
  }
}

class B extends A {
}

在实际实现中,还有其他属性可以区分 B 类和 A 类,但两者都应该具有“getClone”方法。如果在 A 类的对象上调用它应该产生另一个 A 类的对象,如果在 B 类上调用它应该产生另一个 B 类的对象。

当然,我可以通过重写 B 类中的“getClone”并将类名硬编码到方法中来做到这一点(即,$newObj = new B($name)),但最好只对方法进行一次编码,告诉它实例化自己类的对象,无论该类是什么。

PHP 会让我这样做吗?

【问题讨论】:

  • 我不应该将我的方法称为“getClone”或以任何方式暗示克隆。新对象可能与调用其方法的对象非常不同,并且不应复制其任何祖先的内部数据。所以我认为内置克隆不适合我。
  • 同样,我不认为“init()”有帮助,因为我仍然需要从方法中生成并返回一个新的 obj,唯一的方法是最终使用构造函数。很想以其他方式展示。我想我很惊讶没有等同于“父母”的意思是“自我”。
  • 有一个等价的,它可以是selfstatic,这取决于您的需要。

标签: php class methods constructor extends


【解决方案1】:

您不仅可以使用变量,还可以使用与类相关的特殊关键字(例如“self”或“static”)来创建新实例:$newObj = new static($name); - 这将创建当前类的新实例。

您可能应该考虑使用对克隆对象的内置支持:$copy = clone $instance; - 您可以通过指定魔术方法 __clone() 轻松扩展该运算符在类实例上的行为。

class A {
  var $name;
  function __construct($name) {
    $this->name = $name;
  }
  function getClone($name) {
    $newObj = new static($name);
    return $newObj;
  }
}

class B extends A {
}

$tmp = new A('foo');
$a = $tmp->getClone('bar');
// $a instanceof A => true, $a instanceof B => false

$tmp = new B('foo');
$b = $tmp->getClone('bar');
// $b instanceof A => true, $b instanceof B => true

【讨论】:

    【解决方案2】:

    你可以使用

     $clsName = get_class($this);
     return new $clsName();
    

    但 niko 的解决方案也有效,对单例模式很有用 http://php.net/manual/en/language.oop5.static.php

    从 php 5.3 开始,您可以使用 static 关键字的新功能。

    <?php
    
    abstract class Singleton {
    
        protected static $_instance = NULL;
    
        /**
         * Prevent direct object creation
         */
        final private function  __construct() { }
    
        /**
         * Prevent object cloning
         */
        final private function  __clone() { }
    
        /**
         * Returns new or existing Singleton instance
         * @return Singleton
         */
        final public static function getInstance(){
            if( static::$_instance == null){
                static::$_instance = new static();
            }
            return static::$_instance;
        }
        
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      您要做的是使用内置的对象克隆功能http://php.net/manual/en/language.oop5.cloning.php

      但是对于您关于调用构造函数的直接问题,您应该做一个 init() 函数,并将所有 __constructor 代码放入 init() 并让 __constructor 调用 init()

      【讨论】:

      • 感谢您的回答,但我不确定这是我需要的。请。见我上面的新评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2013-08-10
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多