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 } }
The second constructor method
class test { function test()//如果方法名跟类名字一样,将被认为是构造函数 { //your code } }
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()//没有任何输出(其实是有输出,但是输出为空)
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!