---Class creation---
php creates a class using the keyword class and uses a pair of braces
like:
class name{ public $n=""; private $u=""; public function name() { $n="233"; $u="23333"; } public function rename($newn){ $this->n=$newn;//this means this class} }
No semicolons are placed at the end. Then $n and $u are fields; name() is a constructor (__construct() can also define constructors, see below for details), and 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 can be executed, and the latter cannot be declared because private private is not declared before $u. This is similar to C++.
Code:
public static $nm ="2333333333333333" ;
A static field is declared for the function.
This 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, and self is equivalent to $this->.
---Constructor---
Constructors with the same name as the class in php5 and earlier versions
Magic word __construct() can define constructors in php5 and later versions
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 at this time, the default value after = is.
The above is the analysis of PHP classes and constructors introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!