【问题标题】:Php, how to make a parent objectphp,如何制作父对象
【发布时间】:2009-09-27 13:20:01
【问题描述】:

我想知道有没有办法用php创建一个父对象,我试过这个:

new parent::__construct($var);

但它不起作用,我在 php 日志中收到以下错误:

(..)PHP 解析错误:语法错误,意外的 T_STRING,需要 T_VARIABLE 或 '$'(..)

【问题讨论】:

    标签: php multiple-inheritance


    【解决方案1】:

    http://uk.php.net/get_parent_class

    <?php
    class Foo {
    
    }
    
    class Bar extends Foo {
      protected $p;
    
      public function __construct() {
        $pc = get_parent_class();
        $this->p = new $pc;
      }
    }
    
    $bar = new Bar;
    var_dump($bar);
    

    (但不知何故,我不明白你为什么需要这样的东西。但也许这就是我...... ;-))

    【讨论】:

    【解决方案2】:

    只要像这样调用父类的构造函数:

    $parentClassObject = new ParentClassName();
    

    使用 parent::__construct() 调用父类构造函数,因为它在 PHP 中不会自动完成。

    【讨论】:

      【解决方案3】:

      这可能有效:

      $parentClass = get_parent_class();
      $parentObject = new $parentClass();
      

      【讨论】:

        猜你喜欢
        • 2017-03-25
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-26
        • 2011-06-05
        • 2017-05-07
        • 2014-08-24
        相关资源
        最近更新 更多