Home  >  Article  >  Backend Development  >  What is a constructor in php

What is a constructor in php

(*-*)浩
(*-*)浩Original
2019-09-18 14:20:123614browse

php The constructor is a special function in a class. When using the new operator to create an instance of a class, the constructor will be automatically called.

What is a constructor in php

When a function has the same name as a class, this function will become the constructor.

If a class has no constructor, the constructor of the base class is called, if there is one, the constructor is called. (Recommended learning: PHP programming from entry to proficiency)

<?php
class Auto_Cart extends Cart {
    function Auto_Cart(){
        $this -> add_item("10", 1);
    }
}
?>

The above defines an Auto_Cart class, that is, the Cart class plus a constructor, and each time "new" is used to create a When creating a new Auto_Cart class instance, the constructor will be automatically called and the number of an item will be initialized to "10".

Constructors can use parameters, and these parameters can be optional, which can make the constructor more useful. In order to still use the class without parameters, all constructor parameters should provide default values, making them optional.

<?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1){
        $this -> add_item($item, $num);
    }
}
//买些同样的无聊老货
$default_cart = new Constructor_Cart;
//买些实在货...
$different_cart = new Constructor_Cart("20", 17);
?>
void __construct ([mixed $args [, $... ]])

PHP 5 allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time an object is created, so it is very suitable for doing some initialization work before using the object.

Note

If a constructor is defined in a subclass, the constructor of its parent class will not be called secretly. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.

Use the new standard constructor:

<?php
class BaseClass{
    function__construct(){
        print "InBaseClassconstructor\n";
    }
}
 
class SubClass extends BaseClass{
    function__construct(){
        parent::__construct();
        print "InSubClassconstructor\n";
    }
}
 
$obj = new BaseClass();
$obj = new SubClass();
?>

The above is the detailed content of What is a constructor in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn