假設我在php中有一個類,它包含一些函數。OOP PHP類
該課程名爲something
。
當我打開另一個文件中的文件,我注意到它是這樣:
include("the_file_with_the_class.php");
$something = new something(true);
現在我能做的OOP,我知道,像$something->the_function
,但什麼是可變(true)
?這讓我很困惑。
假設我在php中有一個類,它包含一些函數。OOP PHP類
該課程名爲something
。
當我打開另一個文件中的文件,我注意到它是這樣:
include("the_file_with_the_class.php");
$something = new something(true);
現在我能做的OOP,我知道,像$something->the_function
,但什麼是可變(true)
?這讓我很困惑。
在這個例子中你給:
$something = new something(true);
的true
被傳遞到類的構造方法的參數。
如果你在PHP5中,構造函數的方法將被命名爲function __constructor()
。它和其他函數一樣,可以爲它指定參數,並且當你使用new
構造一個對象時,這些函數就會按照你的例子被傳入。
所以在你的例子中,類將有一個參數(大概)需要一個布爾值,並根據該參數的值初始化時執行一些不同的操作。
根據你的代碼,true
是一個參數something
的類構造函數。
的true
是被傳遞給那個類的constructor一個參數一個參數。 構造函數是一個「魔術方法」,正如名稱所述 - 構造對象。
class myclass
{
function __construct($sunnyDay)
{
if ($sunnyDay) echo "It's a sunny day!";
}
}
if ($temperature > 20)
$myclass = new myclass(true); // Outputs "It's a sunny day"