我有3个班..
第1课:
<?php
include "two.php";
include "three.php";
class One{
public function __construct(){
$two = new Two($this);
$three = new Three($two);
}
}
$api = new One;
?>
第2课:
<?php
class Two extends AOP {
public function __construct($obj){
//blablabla
}
}
?>
第3课:
<?php
class Three extends AOP {
public function __construct($obj){
echo get_class($obj);
}
}
?>
但我希望结果必须输出“One”。 如何从对象内的对象获取类名?
答案 0 :(得分:1)
在你的设计中,你必须在第二课中实现一个getter:
第2课:
class Two
{
private $myObj;
public function __construct($obj)
{
$this->myObj = $obj;
}
public function getMyObj()
{
return $this->myObj;
}
}
然后在第3课中,您可以检索第1课:
class Three
{
public function __construct($obj)
{
echo get_class($obj->getMyObj());
}
}
答案 1 :(得分:0)
使用关键字extends
继承另一个类。由于PHP不直接支持多重继承。您可以使用parent::$property;
或parent::method();
来扩展您的课程。所以,你可能希望你的代码看起来更像。
// three.php
class Three extends AOP{
public function __construct($obj){
echo get_class($obj);
}
}
// two.php
class Two extends Three{
public function __construct($obj){
parent::__construct($obj); // Constructors do not return a value echo works
}
protected function whatever($string){
return $string;
}
}
// one.php
include 'three.php'; // must be included first for Two to extend from
include 'two.php'
class One extends Two{
public function __construct(){
// change this part
parent::__construct($this); // uses the parent Constructor
echo $this->whatever('. Is this what you mean?'); // call method without same name in this class - from parent
}
}
$api = new One;
我根本不会使用你的结构,但这应该让你知道继承。