Definition and instantiation methods of php classes

巴扎黑
Release: 2023-03-07 11:06:01
Original
13116 people have browsed it

Definition of php class

A class is the definition of an object. It contains information about how the object behaves, including its name, methods, properties, and events. It's not actually an object itself because it doesn't exist in memory. When the code that references the class runs, a new instance of the class, an object, is created in memory. Although there is only one class, multiple objects of the same type can be created in memory from this class. Classes are defined through the class keyword.

Basic syntax:

class 类名{
   //属性、方法
}
Copy after login

Notes:

1. Define a class (can only be defined with class)

2 .Define the attributes of the class public (public is a modifier, there are three in total, public, protected, private, here we only use public for now)

For example:

Define a car class , the attributes include the color and price of the car

class car{
  public $color;     //定义属性
  public $price;
}
Copy after login

instantiation method of php class

The instantiation of a class is also called creating an object or instantiating an object or converting a class Instantiate.

A simple example:

We define a human class and instantiate this class.

class Preson {                                  //定义了一个Preson类
public $name;                            //定义类的属性(姓名,性别,年龄等等)
public $age;
public $gender;
// public .....
}
//new翻译是新的,意思就是创建一个新的人,并把这个新的对象赋值给$Preson1,这个就是实例化
$Preson1 = new Preson();                 //实例化类
$Preson1->name = "张三";
$Preson1->age = 22;
$Preson1->gender = "女";
echo  $Preson1->name.'  '.$Preson1->age.'  '.$Preson1->gender;
//如果想输出第二个实例,直接输出就OK了,只要改一个变量名
$Preson2 = new Preson();                    //实例化类
$Preson2->name = "小亮";
$Preson2->age = 25;
$Preson2->gender = "男";
Copy after login

The above is the content of this section, the basic concepts of classes and objects and simple instantiation understanding

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

Related labels:
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!