Home  >  Article  >  Backend Development  >  Detailed explanation of php classes and constructors

Detailed explanation of php classes and constructors

怪我咯
怪我咯Original
2017-07-06 09:56:431327browse

This article introduces you to PHP classes and constructor functionsanalysis, including the creation of classes, fields and methods, constructors, etc. It is very good and has reference value. Friends who need it For reference

----Creation of a class----

php uses the keyword class to create a class and uses a Do not put a semicolon at the end of the curly braces

, such as:

class name{
public $n="";
private $u="";
public function name() {
$n="233";
$u="23333";
}
public function rename($newn){
$this->n=$newn;//this表示这个类
}
}

. 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;

with

$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.

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->.

----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 at this time, the default value is the value after =.

The above is the detailed content of Detailed explanation of php classes and constructors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn