search
HomeBackend DevelopmentPHP ProblemIs there a constructor in php?

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.