In-depth understanding of PHP class and constructor analysis

迷茫
Release: 2023-03-06 22:56:02
Original
2134 people have browsed it

Everyone has a certain understanding of classes. Here we only introduce the noteworthy aspects of classes in php

----Creation of classes----

php Use the keyword class to 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表示这个类
  }
}
Copy after login

without a semicolon at the end. Then $n,$u is a field; 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----

Comparison
$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" ;
Copy after login

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

You can also access static fields in the class through self::+$+variable name . At this time, self is equivalent to $this-> ;.

The use of methods is similar to fields


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

The magic word construct() can define a constructor

class name{
  public $n="";
  private $u="";

  public function construct() {
    $n="233";
    $u="23333";
  }

  public function rename($newn){
     $this->n=$newn;
  }
}
Copy after login

The constructor can have parameters



construct($name="",$sex="man",$age=0) {}
When declaring an object

$obj= new name("我","man",28);
Copy after login
If no parameters are given, the value after = will be defaulted.


The above is the detailed content of In-depth understanding of PHP class and constructor analysis. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!