Home >Backend Development >PHP Tutorial >PHP class and constructor analysis
Everyone has a certain understanding of classes. Here we only introduce the noteworthy aspects of classes in php
----Creation of classes----
php uses the keyword class Create a class and use a pair of braces
such as:
class name{ public $n=""; private $u=""; public function name() { $n="233"; $u="23333"; } public function rename($newn){ $this->n=$newn;//this表示这个类 } }
without a 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.
----Field----
Compare
$obj=new name();
echo $obj->n;
with
$obj=new name();
echo $obj->u;
The former is executable, but the latter is not possible because private is declared before $u. This is similar to c++.
Code:
public static $nm ="2333333333333333" ;
Declares a static field for the function.
The variable can be accessed directly 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->.
Methods are used similarly to fields
----Constructor----
Constructed in php5 and earlier versions The function has the same name as the class
In PHP5 and later versions, the magic word __construct() can define the constructor
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 an object
$obj= new name("I","man",28);
If no parameters are given, the default is the value after = .
For more PHP class and constructor analysis related articles, please pay attention to the PHP Chinese website!