【问题标题】:Extension inheritance in PHP?PHP中的扩展继承?
【发布时间】:2018-02-13 01:50:23
【问题描述】:

在使用 C# 进行开发时,您有许多使用相同代码的类,您可以依赖另一个类来保存通用信息,从而更容易修改这些类。

我想知道 PHP 中是否有类似的东西?

class Dog extends Animal {
    private $animalManager

    public function __construct(AnimalManager $animalManager) { 
        $this->animalManager = $animalManager;
    }
}

class Cat extends Animal {
    private $animalManager

    public function __construct(AnimalManager $animalManager) { 
        $this->animalManager = $animalManager;
    }
}

class Fish extends Animal {
    private $animalManager

    public function __construct(AnimalManager $animalManager) { 
        $this->animalManager = $animalManager;
    }
}

class Animal { 
    // Nothing, yet...
}

C# 允许您做的是,以某种方式将 $animalManager 和构造函数赋值存储在“Animal”类中,如果您需要更改它,请将其固定在 1 个位置。

【问题讨论】:

  • PHP 做同样的事情。将公共代码放在Animal的构造函数中,在子类中调用parent::__construct()
  • 阅读 PHP OOP 教程,它应该解释如何使用子类。
  • 你确定你说的是泛型吗?也许继承?

标签: php oop inheritance


【解决方案1】:

问题是,PHP 非常巧妙地做到了这一点。每个扩展类 都从扩展类 继承一切。这意味着只要您调用其中一个扩展类,父级(在本例中为 animal)构造就会运行。

但是,当您在孩子中调用 __construct() 时,您会覆盖您父母的班级。因此,您需要专门调用 parent::__construct() 来运行父构造函数。

class Animal {
    //Private vars can't be directly accessed by children.
    //You'd have to create a function in the parent return it.
    public $animalManager

    //This function will automatically be called if you leave the
    //constructor out of the extended class
    public function __construct($animalManager) { 
        $this->animalManager = $animalManager;
    }

    //If you want $animalManager to be private
    //Call like $fish->getAnimalManager();
    //Though I do not see the use of this.
    public function getAnimalManager(){
      return $this->animalManager
    }
}

class Fish extends Animal {
     //You do not need to do this if you leave the construct out of this class
    public function __construct($animalManager) {
        parent::__construct($animalManager);
        //Do whatever you like here
    }
}

仅包含父构造函数的示例:

class Fish extends Animal {
  //The parent's constructor is called automatically as it's not
  //Being overwritten by this class
  public function test(){
    var_dump($this->animalManager);
  }
}

请注意,您也不需要单独启动父类。就这样称呼吧;

$fish = new Fish(myAnimalManager);
$am = $fish->animalManager;
echo $am;

【讨论】:

  • 谢谢!这完成了工作。
  • 这不能肯定回答 PHP 中的泛型?。这些是原始类型。标题是 SO 从中获得流量的东西。
  • @aniket sahrawat 那是因为我意识到 OP 把他的问题用错了。
  • 如果标题和标签顺便说一句,这就是我提出编辑建议的原因。
【解决方案2】:

Ben Scholzen 为仿制药添加了草稿here

但我只能看到类型参数,没有通配符。它支持泛型函数和泛型构造函数。它还支持边界。

与 C# 和 Java 不同,PHP 将完全具体化其类型参数,这意味着我们可以反射性地知道所需函数/构造函数的运行时参数。

这里不考虑向后兼容性,因为类型参数和原始类型永远无法兼容。所以遗留代码将与泛型不兼容。

【讨论】:

  • 据我所知 - 这只是建议
  • @IlyaBursov 没错,这是草稿。
猜你喜欢
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多