简体   繁体   English

PHP:我可以在“父”类中定义一个新的类实例,并让新实例扩展父类吗?

[英]PHP: Can I define a new class instance inside of a 'parent' class and have the new instance extend the parent

Im wanting to do something like: 我想做类似的事情:

class foo extends bar {
  private $norf = '';
  private $script;

  public function __construct(){
    $this->norf = 'blah blah';
  }

  public function qux(){
    $this->script = new someOtherClass();
    return $this->script->displayNorf();
  }
}

class someOtherClass {
    public function displayNorf(){
        return $this->norf;
    }
}

$test = new foo();
print($test->qux()); //blah blah

This example is really stupid but Im looking for a way to extend the instance of a class. 这个例子确实很愚蠢,但是我正在寻找一种扩展类实例的方法。

Yes, you can create instances of other classes inside your class. 是的,您可以在您的类中创建其他类的实例。 However, your code sample won't work simply because the class someOtherClass does not contain a property named $norf . 但是,您的代码示例将无法正常工作,因为someOtherClass类不包含名为$norf的属性。

$this refers to the current instance of the class, so in someOtherClass->displayNorf() , since the class does not contain a property named $norf you'll receive an undefined property error. $this指向该类的当前实例,因此在someOtherClass->displayNorf() ,由于该类不包含名为$norf的属性,您将收到未定义的属性错误。

In order for this to work, you'll need to change the foo class's property $norf from private to protected and extend the foo class through the someOtherClass class like so: 为了$norf起作用,您需要将foo类的属性$norfprivate更改为protected并通过someOtherClass类扩展foo类,如下所示:

class foo extends bar {
  protected $norf = '';
  private $script;

  public function __construct(){
    $this->norf = 'blah blah';
  }

  public function qux(){
    $this->script = new someOtherClass();
    return $this->script->displayNorf();
  }
}

class someOtherClass extends foo {
    public function displayNorf(){
        return $this->norf;
    }
}

$test = new foo();
print($test->qux()); //blah blah

I think the answer is yes. 我认为答案是肯定的。 If you run the code below, The output will be blah blah . 如果运行下面的代码,则输出为blah blah

<code>
<?php
class foo {
  protected $norf = '';
  private $script;

  public function __construct(){
    $this->norf = 'blah blah';
  }

  public function qux(){
    $this->script = new someOtherClass();
    return $this->script->displayNorf();
  }
}

class someOtherClass extends foo {
    public function displayNorf(){
        return $this->norf;
    }
}
$test = new foo();
print($test->qux()); //blah blah
?>
</code>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM