PHP物件導向-__tostring()和__invoke()的代碼執行個體詳解

來源:互聯網
上載者:User

tostring()魔術方法

  將一個對象當做一個字串來使用時,會自動調用該方法,並且在該方法中,可以返回一定的字串,以表明該對象轉換為字串之後的結果。該魔術方法比較常用。
  注意:如果沒有定義該方法,則對象無法當做字串來使用!

類裡面未定義tostring()方法的例子:

<?phpini_set('display_errors', 1);class A{    public $name;        public $age;        public $sex;         function construct($name, $age, $sex){        $this->name = $name;                $this->age = $age;                $this->sex = $sex;       }}$obj1 = new A('張三', 15, '男');echo $obj1;    //echo 後面為字串,而對象不是字串,會報錯$v1 = "abc" . $obj1;  //.為字串串連符,會報錯$v2 = "abx" + $obj1;  //+為加法運算子,會報錯?>

3個報錯內容分別為

Catchable fatal error: Object of class A could not be converted to stringCatchable fatal error: Object of class A could not be converted to stringNotice: Object of class A could not be converted to int

類裡面定義tostring()方法

<?phpini_set('display_errors', 1);class A{    public $name;        public $age;        public $sex;        function construct($name, $age, $sex){        $this->name = $name;                $this->age = $age;                $this->sex = $sex;       }    function tostring(){        $str = "姓名:" . $this->name;           $str .= "年齡:" . $this->age;            $str .= ",性別:" . $this->sex;                return $str;   //這裡可以返回“任何字串內容”    }}$obj1 = new A('張三', 15, '男');echo $obj1;    //調用tostring(),不會報錯?>

運行結果

姓名:張三年齡:15,性別:男

invoke()魔術方法

  將對象當作函數來使用時,會自動調用該方法。通常不推薦這麼做。

class A{    function invoke(){        echo "<br />我是一個對象呀,你別把我當作一個函數來調用啊!";    }}$obj = new A();$obj();    //此時就會調用類中的方法:invoke()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.