php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

php中的构造函数

在PHP里,如果你没有手写构造函数,则php在实例化这个对象的时候,会自动为类成员以及类方法进行初始化,分配内存等工作,但是有些时候不能满足我们的要求,比如我们要在对象实例化的时候传递参数,那么就需要手动编写构造函数了,手写构造函数有两种写法,只是表现形式不同,其实本质一样。

第一种构造函数的方法

class test
{
    function __construct()
    {
     //your code
    }
}

第二种构造函数的方法

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

传递参数进行实例化的示例

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()//没有任何输出(其实是有输出,但是输出为空)


构造函数在php中的使用方法(附示例)