本文實例講述了PHP面向對象程序設計__tostring()和__invoke()用法。分享給大家供大家參考,具體如下:
__tostring()
魔術方法
將一個對象當做一個字符串來使用時,會自動調用該方法,并且在該方法中,可以返回一定的字符串,以表明該對象轉換為字符串之后的結果。該魔術方法比較常用。
注意:如果沒有定義該方法,則對象無法當做字符串來使用!
類里面未定義__tostring()
方法的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php ini_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 string
Catchable fatal error: Object of class A could not be converted to string
Notice: Object of class A could not be converted to int
類里面定義__tostring()
方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php ini_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()
魔術方法
將對象當作函數來使用時,會自動調用該方法。通常不推薦這么做。
1
2
3
4
5
6
7
|
class A{ function __invoke(){ echo "<br />我是一個對象呀,你別把我當作一個函數來調用啊!" ; } } $obj = new A(); $obj (); //此時就會調用類中的方法:__invoke() |
希望本文所述對大家PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/Yeoman92/article/details/52851906