PHP toString 魔术方法

问题描述 投票:0回答:2

如果我在一个 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;

但只出现第一个!

php tostring magic-methods
2个回答
1
投票

我忘记回显另一个类实例,我的错! 答案是在最后的代码中添加 echo $ph 抱歉!!


0
投票
$mars = new Planete(); $mars->setNom("Mars"); $mars->setRayon(3397); 
$mars->setGravitation(3.69);

echo $mars;  //* you should add echo to this line! *//

$ph = new Satellite(); $ph->setNom("Phobos"); 
$ph->setPlanete($mars->getNom());
$ph->setRotation(0.32);
echo $mars;
© www.soinside.com 2019 - 2024. All rights reserved.