简体   繁体   English

无法理解__toString()函数OOP PHP

[英]Unable to understand __toString() function OOP PHP

I am now learning object oriented php and i face a problem with the magic method named __toString(). 我现在正在学习面向对象的php,我遇到了一个名为__toString()的魔术方法。

There are no calls for that function. 没有对该函数的调用。 Is it similar to other magical function? 它与其他神奇功能相似吗?

If a use it to my class then is it convert all the objects all string or not? 如果将其用于我的班级,那么是否将所有对象都转换为字符串?

Code- 码-

class MyClass
{
  public $prop1 = "I'm a class property!";

  public function __construct()
  {
      echo 'The class "', __CLASS__, '" was initiated!<br />';
  }

  public function __destruct()
  {
      echo 'The class "', __CLASS__, '" was destroyed.<br />';
  }

  public function __toString()
  {
      echo "Using the toString method: ";
      return $this->getProperty();
  }

  public function setProperty($newval)
  {
      $this->prop1 = $newval;
  }

  public function getProperty()
  {
      return $this->prop1 . "<br />";
  }
}

// Create a new object
$obj = new MyClass;

// Output the object as a string
echo $obj;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>

The output- 输出-

The class "MyClass" was initiated! Using the toString method: I'm a class property! The class "MyClass" was destroyed. End of file.

The magic __toString method is called when an object of that class is getting used as a string: 当该类的对象用作字符串时,将调用魔术__toString方法:

class Something {
    private $whatever;
    public function __construct($whatever) {
        $this->whatever = $whatever;
    }
    public function __toString() {
        return $this->whatever;
    }
}

$obj = new Something("Whatever here!");
echo "Object is $obj"; // Object is Whatever here!

See The Docs . 请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM