Home > Article > Backend Development > PHP classes and constructors
This article introduces you to the analysis of PHP classes and constructors, including the creation of classes, fields and methods, constructors, etc. It is very good and has reference value. Friends who need it can refer to it
----Creation of a class----
php uses the keyword class to create a class and uses a pair of curly brackets
For example:
class name{ public $n=""; private $u=""; public function name() { $n="233"; $u="23333"; } public function rename($newn){ $this->n=$newn;//this表示这个类 } }
No semicolon at the end. Then $n, $u are fields; name() is a constructor (__construct() can also define a constructor, see below for details), which can assign values to fields; rename() is a method.
----Fields and methods----
Compare
$obj=new name(); echo $obj->n;
and
$obj=new name(); echo $obj->u;
The former is executable, but the latter is not possible because $u declares private before. This is similar to c.
Code:
public static $nm ="2333333333333333" ;
Declares a static field for the function.
You can directly access the variable through the class name and ::
echo name::$nm;
This is also similar to c.
In php, you can also access static fields in the class through self:: $ variable name. At this time, self is equivalent to $this->.
----Constructor----
In php5 and earlier versions, the constructor has the same name as the class
In php5 and later versions, the magic word __construct() can define the constructor
class name{ public $n=""; private $u=""; public function __construct() { $n="233"; $u="23333"; } public function rename($newn){ $this->n=$newn; } }
The constructor can have parameters
__construct($name="",$sex="man",$age=0){}
When declaring the object
$obj= new name("我","man",28);
If no parameters are given, the value after = will be defaulted.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
JavaScript Constructor and new operator (key, must read)
javascript Constructor way to define objects
The above is the detailed content of PHP classes and constructors. For more information, please follow other related articles on the PHP Chinese website!