About the definition and instantiation method of php class

藏色散人
Release: 2023-04-07 22:44:02
forward
2571 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, they are public, protected, and private. Here we only use public for now)

For example:

Define a car class with the color of the car as an attribute And price

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 instantiating a class.

A simple example:

We define a human class and instantiate this class.

class Preson {                               //定义了一个Preson类
public $name = ‘aaa’;                //定义类的属性(姓名,性别,年龄等等)
public $age = ‘2’;
public $gender = ‘男’;
}
//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 basic concepts and simple instantiation understanding of classes and objects.

The above is the detailed content of About the definition and instantiation method of php class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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!