【发布时间】:2015-09-13 01:33:51
【问题描述】:
如果我在一个 php 文件中创建两个类,并为这两个类定义魔术方法 __toString(),其中哪一个将被执行?因为我已经这样做了,其中一个被执行了...我只是不不知道为什么?
public function __toString(){
return $this->pla_id." Nom = ".$this->pla_nom.", Rayon = ".$this->pla_rayon.", Gravitation = ".$this->pla_gravitation;
}
public function __toString(){
return $this->sat_id." ".$this->sat_nom." ".$this->sat_rayon." ".$this->sat_rotation;
}
在另一个文件中:
$mars = new Planete(); $mars->setNom("Mars"); $mars->setRayon(3397);
$mars->setGravitation(3.69);
$ph = new Satellite(); $ph->setNom("Phobos");
$ph->setPlanete($mars->getNom()); $ph->setRotation(0.32);
echo $mars;
但只有第一个出现!
【问题讨论】:
-
也可以试试
echo $ph;看看函数覆盖的魔力。 -
我知道我忘记了!但是如何用一个 tostring 显示两个类的变量(例如(姓名,年龄...)?
-
在子类的
__toString方法中调用parent::__toString();。 -
public function __toString(){ $str = parent::__toString(); return $str.'\n'.$this->sat_id." ".$this->sat_nom." ".$this->sat_rayon." ".$this->sat_rotation; }
标签: php tostring magic-methods