通过引用传递给父PHP类

时间:2014-12-03 13:03:28

标签: php oop

如何通过引用传递对象?

我有以下脚本,并收到以下错误。

  

严格标准:myChild :: myMethod()的声明应该是   兼容myParent :: myMethod($ id = NULL,& $ model = NULL)in   第19行/var/www/bidjunction/html/testing/passbyreference.php

<?php
class myParent
{
    public function myMethod($id=null,&$model=null)
    {
        $model=$model?$model:new stdClass();
        var_dump($model);
    }
}

class myChild extends myParent
{
    public function myMethod($id=null,$model=null)
    {
        $model=new stdClass();
        $model->foo='bar';
        parent::myMethod(123,$model);
    }
}
class myOtherChild extends myParent{}

$myChild=new myChild();
$myChild->myMethod();

$myOtherChild=new myChild();
$myOtherChild->myMethod();
?>

3 个答案:

答案 0 :(得分:2)

我将提供一些有关错误的一般信息。抛出它是因为方法参数不一样。您的父类需要一个指向引用的指针,而您的孩子期望实例本身。如果覆盖函数,则方法名称和参数必须相同。

改变它,所以他们都期望一个指针:

class myParent
{
    public function myMethod($id=null,&$model=null)
    {
    }
}

class myChild extends myParent
{
    public function myMethod($id=null,&$model=null)
    {
    }
}

或者他们都期待实例

class myParent
{
    public function myMethod($id=null,$model=null)
    {
    }
}

class myChild extends myParent
{
    public function myMethod($id=null,$model=null)
    {
    }
}

答案 1 :(得分:0)

正如安德鲁在评论中所说。在覆盖子级或继承类中的方法时,根据LISKOV替换原则,两种方法中的方法签名应该相同。

http://en.wikipedia.org/wiki/Liskov_substitution_principle

答案 2 :(得分:0)

当你扩展一个类时,如果你希望父类能够访问你必须注入它的子类,你就可以扩展该类类型而不是它的实例

class myParent
{

   public $child;

   public function addChild($child){
      $this->child = $child;
   }


}

$myParent = new parent();

$myChild=new myChild();

$myParent->addChild($myChild);