簡體   English   中英

無法理解__toString()函數OOP PHP

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

我現在正在學習面向對象的php,我遇到了一個名為__toString()的魔術方法。

沒有對該函數的調用。 它與其他神奇功能相似嗎?

如果將其用於我的班級,那么是否將所有對象都轉換為字符串?

碼-

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 class "MyClass" was initiated! Using the toString method: I'm a class property! The class "MyClass" was destroyed. End of file.

當該類的對象用作字符串時,將調用魔術__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!

請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM