【问题标题】:Magic method toString PHP魔术方法 toString PHP
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2010-10-27
    • 1970-01-01
    • 2011-06-10
    • 2010-12-26
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多