Purpose of PHP constructors

后端 未结 6 1711
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 20:14

I am working with classes and object class structure, but not at a complex level – just classes and functions, then, in one place, instantiation.

As to __const

6条回答
  •  抹茶落季
    2020-11-30 20:41

    The constructor is run at the time you instantiate an instance of your class. So if you have a class Person:

    class Person {
    
        public $name = 'Bob'; // this is initialization
        public $age;
    
        public function __construct($name = '') {
            if (!empty($name)) {
                $this->name = $name;
            }
        }
    
        public function introduce() {
            echo "I'm {$this->name} and I'm {$this->age} years old\n";
        }
    
        public function __destruct() {
            echo "Bye for now\n";
        }
    }
    

    To demonstrate:

    $person = new Person;
    $person->age = 20;
    $person->introduce();
    
    // I'm Bob and I'm 20 years old
    // Bye for now
    

    We can override the default value set with initialization via the constructor argument:

    $person = new Person('Fred');
    $person->age = 20;
    $person->introduce();
    
    // if there are no other references to $person and 
    // unset($person) is called, the script ends 
    // or exit() is called __destruct() runs
    unset($person);
    
    // I'm Fred and I'm 20 years old
    // Bye for now
    

    Hopefully that helps demonstrate where the constructor and destructor are called, what are they useful for?

    1. __construct() can default class members with resources or more complex data structures.
    2. __destruct() can free resources like file and database handles.
    3. The constructor is often used for class composition or constructor injection of required dependencies.

提交回复
热议问题