Home  >  Article  >  Backend Development  >  Is there a constructor in php?

Is there a constructor in php?

藏色散人
藏色散人Original
2022-01-26 10:04:381771browse

There is a constructor in php, and its syntax description is "__construct(mixed...$values ​​= ""): void". A class with a constructor will call this method first every time it creates a new object. , so it is very suitable for doing some initialization work before using the object.

Is there a constructor in php?

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

Is there a constructor in php?

php Constructor

__construct(mixed ...$values = ""): void

PHP allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time a new 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 implicitly called. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor. If the subclass does not define a constructor, it will be inherited from the parent class like an ordinary class method (if it is not defined as private).

Example #1 Constructor in inheritance

<?php
class BaseClass {
    function __construct() {
        print "In BaseClass constructor\n";
    }
}
class SubClass extends BaseClass {
    function __construct() {
        parent::__construct();
        print "In SubClass constructor\n";
    }
}
class OtherSubClass extends BaseClass {
    // 继承 BaseClass 的构造函数
}
// In BaseClass constructor
$obj = new BaseClass();
// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();
// In BaseClass constructor
$obj = new OtherSubClass();
?>

Unlike other methods, __construct() is not subject to signature compatibility rules when inheriting.

Since PHP 5.3.3, in the namespace, methods with the same name as the class name are no longer used as constructors. Classes that are not in the namespace are not affected. The constructor is a normal method that is automatically called when the corresponding object is instantiated. Therefore, any number of parameters can be defined, which can be required, have types, or have default values. The parameters of the constructor are placed in parentheses after the class name.

Example #2 Using constructor parameters

<?php
class Point {
    protected int $x;
    protected int $y;
    public function __construct(int $x, int $y = 0) {
        $this->x = $x;
        $this->y = $y;
    }
}
// 两个参数都传入
$p1 = new Point(4, 5);
// 仅传入必填的参数。 $y 会默认取值 0。
$p2 = new Point(4);
// 使用命名参数(PHP 8.0 起):
$p3 = new Point(y: 5, x: 4);
?>

If a class does not have a constructor and the parameters of the constructor are not required, the parentheses can be omitted.

Old-style constructor

Before PHP 8.0.0, if a class in the global namespace had a method with the same name, it would be resolved to an old-style constructor device. Although functions can be used as constructors, this syntax is deprecated and results in an E_DEPRECATED error. If __construct() and a method of the same name exist at the same time, __construct() will be called.

Methods with the same name as the class no longer have special meaning in the following two cases: classes in the namespace, and any class since PHP 8.0.0.

Use __construct() in new code.

Constructor attribute promotion

Starting from PHP 8.0.0, the parameters of the constructor can also be promoted to class attributes accordingly. It is common for constructor parameters to be assigned to class attributes, otherwise it cannot be operated. The function of constructor promotion provides convenience for this scenario. So the above example can be rewritten in the following way:

Example #3 Using constructor attribute promotion

<?php
class Point {
    public function __construct(protected int $x, protected int $y = 0) {
    }
}

When the constructor parameter has access control (visibility modifier) , PHP will treat it as an object property and a constructor parameter at the same time, and assign it to the property. The constructor can be empty or contain other statements. After the parameter value is assigned to the corresponding attribute, additional code statements in the text are executed.

Not all parameters need to be improved. It is possible to have a mixture of promoted and non-promoted parameters as attributes, and they do not need to be in order. Raised parameters do not affect code calls within the constructor.

Note:

The type of object properties cannot be callable to avoid confusion for the engine. Therefore the promoted parameter cannot be callable either. Any other type declarations are allowed.

Note:

The properties placed in the constructor's hoisting parameters will be copied as properties and parameters at the same time.

Static creation method

Each class in PHP can only have one constructor. However, there are situations where objects need to be constructed in different ways with different inputs. In this case it is recommended to use static method wrapping construct.

Example #4 Using static to create a method

<?php
class Product {
    private ?int $id;
    private ?string $name;
    private function __construct(?int $id = null, ?string $name = null) {
        $this->id = $id;
        $this->name = $name;
    }
    public static function fromBasicData(int $id, string $name): static {
        $new = new static($id, $name);
        return $new;
    }
    public static function fromJson(string $json): static {
        $data = json_decode($json);
        return new static($data[&#39;id&#39;], $data[&#39;name&#39;]);
    }
    public static function fromXml(string $xml): static {
        // 自定义代码逻辑。
        $data = convert_xml_to_array($xml);
        $new = new static();
        $new->id = $data[&#39;id&#39;];
        $new->name = $data[&#39;name&#39;];
        return $new;
    }
}
$p1 = Product::fromBasicData(5, &#39;Widget&#39;);
$p2 = Product::fromJson($some_json_string);
$p3 = Product::fromXml($some_xml_string);

You can set the constructor to private or protected to prevent additional calls by yourself. At this time only static methods can instantiate a class. Since they are in the same defined class they can access private methods and do not need to be in the same object instance. Of course, the constructor does not have to be set to private. Whether it is reasonable depends on the actual situation.

Three static methods show how objects are instantiated in different ways.

  • fromBasicData() Pass all required parameters into the constructor, create the object and return the result.

  • fromJson() accepts a JSON string, preprocesses it into the format required by the constructor, and returns a new object.

  • fromXml() accepts an XML string, parses it, and creates a simple object. Since the parameters are optional, the constructor can be called with all parameters ignored. Then assign values ​​to the properties of the object and return the result.

In the above three examples, the static keyword will be translated into the class name of the class where the code is located. In this case it's Product.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Is there 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