Home > Backend Development > PHP Tutorial > How to use constructor in php (with examples)

How to use constructor in php (with examples)

烟雨青岚
Release: 2023-04-08 19:32:01
forward
3067 people have browsed it

How to use constructor in php (with examples)

Constructor in php

In PHP, if you do not have a handwritten constructor, php is in the instance When this object is instantiated, it will automatically initialize class members and class methods, allocate memory, etc. However, sometimes it cannot meet our requirements. For example, if we want to pass parameters when instantiating the object, we need to manually write the constructor. Yes, there are two ways to write handwritten constructors, but the expressions are different, but the essence is the same.

The first constructor method

class test
{
    function __construct()
    {
     //your code
    }
}
Copy after login

The second constructor method

class test
{
    function test()//如果方法名跟类名字一样,将被认为是构造函数
    {
    //your code
    }
}
Copy after login

Pass Example of parameter instantiation

class test
{
    public $test = '';
    function __construct($input = '')
    {
        $this->test = $input;
    }
    function getTest()
    {
        return $this->test;
    }
}
$a = new test('a test');
echo $a->getTest()//将输出 a test
$b = new test();
echo $a->getTest()//没有任何输出(其实是有输出,但是输出为空)
Copy after login

Recommended tutorial: "PHP Tutorial"

Thank you for reading, I hope you will benefit.

The above is the detailed content of How to use constructor in php (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template