假设我在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"