Benefits of using a constructor?

前端 未结 5 1537
眼角桃花
眼角桃花 2020-12-10 07:49

In my quest in trying to learn more about OOP in PHP. I have come across the constructor function a good few times and simply can\'t ignore it anymore. In my understanding,

5条回答
  •  被撕碎了的回忆
    2020-12-10 08:26

    Yes the constructor is called when the object is created.

    A small example of the usefulness of a constructor is this

    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);
    

    UPDATE: A question also asked why this should be used, a real life example is a database class, where you call the object with the username and password and table to connect to, which the constructor would connect to. Then you have the functions to do all the work within that database.

提交回复
热议问题