Benefits of using a constructor?

前端 未结 5 1525
眼角桃花
眼角桃花 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:05

    The constructor allows you to ensure that the object is put in a particular state before you attempt to use it. For example, if your object has certain properties that are required for it to be used, you could initialize them in the constructor. Also, constructors allow a efficient way to initialize objects.

    0 讨论(0)
  • 2020-12-10 08:06

    The constructor is for initialisation done when an object is created.

    You would not want to call an arbitrary method on a newly created object because this goes against the idea of encapsulation, and would require code using this object to have inherent knowledge of its inner workings (and requires more effort).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 08:26

    The idea of constructor is to prepare initial bunch of data for the object, so it can behave expectedly.

    Just call a method is not a deal, because you can forget to do that, and this cannot be specified as "required before work" in syntax - so you'll get "broken" object.

    0 讨论(0)
  • 2020-12-10 08:30

    Constructors are good for a variety of things. They initialize variables in your class. Say you are creating a BankAccount class. $b = new BankAccount(60); has a constructor that gives the bank account an initial value. They set variables within the class basically or they can also initialize other classes (inheritance).

    0 讨论(0)
提交回复
热议问题