求教:类中的类
php吧
全部回复
仅看楼主
level 12
合耳 楼主
class foot { protected $size = 1; protected $shape = 'boat';}
class leg { protected $length = 12; protected $width = 3;}
class body { protected foot $myfoot; protected leg $myleg;}
$mybody = new body;
定义一个脚的类,定义一个腿的类,这个都很常规,容易实现。
现在的问题是,我要定义一个身体的类,而身体的类里面,想要包含脚和腿的类,实现:$mybody->myleg->size.
怎么定义?能实现吗?
2023年11月17日 03点11分 1
level 12
合耳 楼主
PHP 不支持多重继承
2023年11月17日 07点11分 2
网页链接 问一下GPT4
2023年11月17日 15点11分
level 12
多继承用trait模拟,PHP用组合代替了继承。
另外$mybody->myleg->size这种语法难道不是把对象定义为属性,这跟多继承有什么关系?
2023年11月17日 10点11分 3
level 6
——以下由AI回答,仅供参考——
可以实现,如下:
class foot {
protected $size = 1;
protected $shape = 'boat';
}
class leg {
protected $length = 12;
protected $width = 3;
}
class body {
protected foot $myfoot;
protected leg $myleg;
public function __construct() {
$this->myfoot = new foot();
$this->myleg = new leg();
}
public function getMylegSize() {
return $this->myleg->size;
}
}
$mybody = new body();
echo $mybody->getMylegSize(); // 1
2023年11月17日 11点11分 4
这层正解
2023年11月17日 13点11分
level 1
哦哦,这样啊
2023年11月18日 14点11分 5
level 12
合耳 楼主
谢谢各位大佬。
这个问题的关键,其实就是类的定义中,必须要有实例,而不能是抽象的。
2023年11月20日 00点11分 6
1