Kei*_*gan 6 php oop constructor
在我试图在PHP中学习更多关于OOP的过程中.我几次遇到构造函数,根本不能忽略它.在我的理解中,构造函数在我创建对象的那一刻被调用,这是正确的吗?
但是,如果我可以使用"普通"函数或方法作为调用,为什么我需要创建这个构造函数呢?
干杯,基思
Óla*_*age 10
是的,在创建对象时调用构造函数.
构造函数的有用性的一个小例子是这样的
class Bar
{
    // The variable we will be using within our class
    var $val;
    // This function is called when someone does $foo = new Bar();
    // But this constructor has also an $var within its definition,
    // So you have to do $foo = new Bar("some data")
    function __construct($var)
    {
        // Assign's the $var from the constructor to the $val variable 
        // we defined above
        $this->val = $var
    }
}
$foo = new Bar("baz");
echo $foo->val // baz
// You can also do this to see everything defined within the class
print_r($foo);
更新:一个问题也问为什么应该使用它,一个真实的例子是一个数据库类,你可以使用用户名和密码以及连接到的表来调用对象,构造函数将连接到该对象.然后,您具有在该数据库中完成所有工作的功能.
构造函数的想法是为对象准备初始数据束,因此它可以表现出预期的行为.
Just call a method 这不是一个交易,因为你可以忘记这样做,并且这不能在语法中指定为"工作前需要" - 所以你将得到"破碎"的对象.