PHP basic tutorial nine classes and objects

黄舟
Release: 2023-03-06 08:56:01
Original
1461 people have browsed it

Content explained in this section

  • Classes and objects

  • The composition of classes

  • Creation of objects

  • PHP garbage collection mechanism

  • $this explanation

Preface

PHP is an object-oriented programming language, so what is object-oriented? Why should we be object-oriented? There are many things in our lives that are objects, such as a cup, a box, etc. They all have their own unique characteristics and they are all objects. And our development in development is also based on object-oriented programming. An object is anything that people want to study, from the simplest integers to complex airplanes. Our use of object-oriented programming can enable us to see the problem comprehensively, and it is also conducive to the management and maintenance of data. In PHP, object-oriented programming can be divided into two categories, one is models, which create objects for use, and the other is objects. , created using models, so what is the relationship between the two of them?

Classes and Objects

Classes and Objects: The abstraction of objects with the same characteristics (data elements) and behavior (functions) is a class. Therefore, the abstraction of an object is a class, and the concretization of a class is an object. It can also be said that an instance of a class is an object, and a class is actually a data type.

That is to say, extracting the functions and characteristics of the object to form a class is like extracting the model of a cup, and we can create various cups (also known as cups) based on this model (that is, the class) is the object).
So how are classes defined? How are objects created?

Composition of a class

<?php

    class Cat{ //定义一个猫类
        public $name; //猫的名字
        public $age;//猫的名字
        public $color;//猫的颜色
        //猫的构造方法
        public function __construct(){

        }

        public function sleep(){
            echo &#39;猫睡觉&#39;;
        }

        public function eat(){
            echo &#39;猫吃饭&#39;;
        }

    }
Copy after login

The above is the basic structure of a class. Below we will explain the meaning of each part in detail.

  • class is a keyword and cannot be modified, indicating that this is a class.

  • Cat is the class name. The class name is written starting with a capital letter and named in camel case.

Class attributes

Attributes: Member attributes are a component of the class, generally basic data types (integers, strings, etc.) , it can also be a composite type (object, array), resource type. For example, the public $age of the cat class we defined earlier is a member attribute.

It can be said that each class has attributes. The attributes of a class are the characteristics of a class. For example, a cat can have a name, age, color, etc., which are common characteristics of cats. We call this feature in a class an attribute. Of course, we don’t need to define an attribute. This depends on your own needs.

The public in front of the attribute is a permission modifier, which will be explained later.

Member method (function)

In the above code, you can see that there are several functions in the class. They are the same as the previous functions, but There is an additional permission control character in front. It can also be called member methods. These member methods are the behaviors in the class. For example, the cat class above has the behavior of sleeping and eating. Of course, you can write its own behavior.

Member method syntax:

访问修饰符  function  函数名(形式参数){
    //函数体;
    //return 返回值;
}
Copy after login
  • Access modifiers, there are three types (public, protected, privte), the default is public, we will explain it in detail later

  • Other parts are the same as the functions we learned, including the calling mechanism

  • The parameter list can have multiple and can be of any type

  • For the return value of the method, this can depend on the specific requirements.

  • Member methods are defined in the class. If they are defined outside the class, it will not be the behavior of this class.

Constructor

There is a method in the cat class above, the method name is -__construct(), this is a constructor, so what Is it a constructor? The constructor is a method of initializing data when creating an object. For example, if we want to directly give the cat's name, age and color to it when creating an object, we can use the constructor.

public function __construct($name,$age,$color){
            $this-> name = $name;
            $this-> age = $age;
            $this-> color = $color;
}
Copy after login

The syntax of the constructor is:

public  function  __construct(形式参数){  
    //函数体
}
Copy after login

For the method name of the constructor __construct(), this is a magic method, which will be introduced later. In fact, there is another way to write the constructor, The method name of the constructor is the name of the class:

public function Cat($name,$age,$color){

}
Copy after login

The above constructor method definition is also correct, but it is recommended to use the magic method (__construct()), thinking that when our class name occurs When it changes, there is no need to modify it.

NoteThe names of classes in PHP are not case-sensitive, but we still have to write them in uppercase and lowercase. At the same time, the constructor has no return value.

Constructors need to pay attention to:

  • In a class, there can only be one constructor, this is a mandatory requirement

  • The constructor is automatically called by the system , we don’t need to adjust it ourselves.

  • If we do not define a constructor, the system will use a default constructor with the following form: public function

  • __construct(){ }, so whether we have defined a constructor or not, it has a constructor.

上面的三种情况就是类中大致的内容,在后续我们还会降类中的其他情况。

对象的创建

在上面创建对象的类已经有了,那么怎么创建对象呢?

对象创建方法

$cat = new Cat();
Copy after login

创建对象的语法是:

$对象名 = new 类名(参数1,参数2);
Copy after login

类名后面的括号里的参数是传递给类的构造函数的,如果构造函数没有参数,可以不写。

  • 对象的命名规范和普通变量一样,使用驼峰法或者下划线法均可

  • new也是一个关键字,不能修改,表示新创建对象

我们创建对象的目的就是需要操作对象,而操作对象,就是操作对象里面的属性和方法。

在上面的类下面写如下代码:

//创建对象,传递三个参数到构造函数。
$cat = new Cat(&#39;小花&#39;,12,&#39;black&#39;);
//通过对象来访问对象的属性
echo $cat -> name;
echo &#39;<br>&#39;;
echo $cat -> age;
echo &#39;<br>&#39;;
echo $cat -> color;
echo &#39;<br>&#39;;
$cat-> sleep();
$cat-> eat();
.....结果......
小花
12
black
猫睡觉
猫吃饭
Copy after login

上面的对象通过->访问属性和方法。注意属性的前面没有$符号

$对象名->属性名= 值;
echo  $对象名->属性名;
&#39;-> &#39; 称为对象运算符.
Copy after login

上面的就是对象的创建和最基本的应用

对象的传递类型

当我们把对象的值赋给另外一个变量是,是值传递还是引用传递?

    //创建一个对象
    $cat = new Cat(&#39;小花&#39;,12,&#39;black&#39;);
    $cat1 = $cat; // 把$cat这个对象赋给$cat1;
    $cat1 -> name = &#39;小白&#39;;//利用$cat1这个对象修改对象的名字。
    echo $cat1 -> name; //输出$cat1对象的名字。
    echo &#39;<br>&#39;;
    echo $cat -> name; //输出$cat对象的名字。
.....结果......
小白
小白
Copy after login

看到这里可能有点蒙,不是值传递吗?怎么修改一个对象的属性,另外一也变了?,

上面的代码当中 $cat1=$cat也是值传递,但是这个值是对象的引用(可以理解对象标识符),即每个包含对象的变量都持有对象的引(reference),而不是整个对象的拷贝。

PHP basic tutorial nine classes and objects

在上面的图中可以看到,当$cat赋值给$cat1时,也就是对象标识符(#1)复制了一份,赋给$cat1,其实他们还是指向同一块数据区,所以只要其中一个修改了值,另外一个也会变。

对象的销毁

我们使用完对象后,已经确定在以后不会使用这个对象了,这个时候我们可以手动的销毁对象,那么我们怎么让对象销毁呢?

  1. 当没有任何变量指向对象时,会销毁,因此我们可以把对象引用置为null

  2. 使用unset()函数来销毁对象。

    //创建一个对象
    $cat = new Cat(&#39;小花&#39;,12,&#39;black&#39;);
    $cat -> sleep();
    unset($cat);
    $cat -> sleep();
    .....结果.....
    
    猫睡觉
    Notice: Undefined variable: cat in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\object.php on line 27
    
    Fatal error: Call to a member function sleep() on null in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\object.php on line 27
    Copy after login

    其实在一个文件运行完的时候,PHP会启动垃圾回收机制,自动的进行垃圾回收。这时候在里面创建的对象就自动销毁了,那么什么是PHP的垃圾回收机制?

PHP垃圾回收机制

垃圾回收,顾名思义,回收垃圾的,在程序中启动垃圾回收机制的时机:

  • 在php中,当一个对象没有任何引用指向它的时候,就会成为一个垃圾对象,php将启动垃圾回收器将对象销毁。

  • 当程序退出前,php也将启用垃圾回收器,销毁对象。

那么什么是垃圾回收机制?

垃圾回收机制是php5之后才有的,php5.3之前使用的垃圾回收机制是单纯的“引用计数”,也就是每个内存对象都分配一个计数器,当内存对象被变量引用时,计数器+1;当变量引用撤掉后,计数器-1;当计数器=0时,表明内存对象没有被使用,该内存对象则进行销毁,垃圾回收完成。但是PHP5.3开始,使用了新的垃圾回收机制,在引用计数基础上,实现了一种复杂的算法,来检测内存对象中引用环的存在(对象的相互引用),以避免内存泄漏。

$this说明

在上面写类的构造函数的时候,可以看到在函数中使用到了$this,那么在面向对象中$this是什么?

$this是在类中使用的访问自身的一种机制。系统会给每个对象分配$this,代表当前对象。通俗的说就是在当前环境下,谁调用,$this就代表哪个对象。

<?php

    class Cat{ //定义一个猫类
        public $name; //猫的名字
        public $age;//猫的名字
        public $color;//猫的颜色
        //猫的定义方法
        public function Cat($name,$age,$color){
            $this-> name = $name;
            $this-> age = $age;
            $this-> color = $color;
        }

        public function sleep(){
            echo &#39;猫睡觉<br>&#39;;
        }

        public function eat(){
            echo &#39;猫吃饭<br>&#39;;
        }
        //输出猫的信息
        public function info(){
            echo &#39;猫的名字是&#39; . $this -> name . &#39; 年龄是&#39; . $this-> age . &#39; 颜色是&#39; . $this-> color;
        }

    }
    //创建一个对象
    $cat = new Cat(&#39;小花&#39;,12,&#39;black&#39;);
    $cat -> info();
    echo &#39;<br>&#39;;
    //创建另一个对象,传进不同的属性
    $cat1 = new Cat(&#39;小白&#39;,6,&#39;white&#39;);
    $cat1 -> info();
    .....结果.....
猫的名字是小花 年龄是12 颜色是black
猫的名字是小白 年龄是6 颜色是white
Copy after login

在上面的类中的info()函数中使用$this,不同的对象输出不同的结果,因为在不同的环境下,谁调用,$this就代表哪个对象。

类的析构函数

在上面我们提到过,对象的销毁,其实在类中有一个方法,就是在对象销毁的时候由系统自动执行的。我们称之为析构函数。

public function __destruct(){
        echo $this->name . &#39;被销毁了<br>&#39;;
}
Copy after login

在PHP5中引入了析构函数的概念,析构函数会在某个对象的所有引用被删除(没有变量指向对象,要被销毁了),对象销毁前执行。

析构函数的主要作用是去释放对象分配的相关资源,比如数据库连接或打开的文件等。

它的语法是:

function  __destruct(){
    //函数体[释放资源,比如数据库连接,或者打开文件等等]
}
Copy after login

析构函数也是系统自动调用的,我们不用自己调。但是当我们没有写析构函数的时候,系统不会执行析构函数。

<?php

class Cat{ //定义一个猫类
    public $name; //猫的名字
    public $age;//猫的名字
    public $color;//猫的颜色
    //猫的定义方法
    public function Cat($name,$age,$color){
        $this-> name = $name;
        $this-> age = $age;
        $this-> color = $color;
    }

    public function sleep(){
        echo &#39;猫睡觉<br>&#39;;
    }

    public function eat(){
        echo &#39;猫吃饭<br>&#39;;
    }
    //输出猫的信息
    public function info(){
        echo &#39;猫的名字是&#39; . $this -> name . &#39; 年龄是&#39; . $this-> age . &#39; 颜色是&#39; . $this-> color;
    }

    public function __destruct(){
        echo $this->name . &#39;被销毁了<br>&#39;;
    }

}
//创建一个对象
$cat = new Cat(&#39;小花&#39;,12,&#39;black&#39;);
echo $cat -> name; //输出对象的名字
echo &#39;<br>&#39;;
unset($cat); //销毁对象,系统自动调用析构函数。
.....结果......
小花
小花被销毁了
Copy after login

当我们销毁对象$cat时,析构函数自动执行。

  • The destructor is automatically executed before the object is destroyed, and it has no return value. There can only be one destructor in a class.

  • The destructor destroys the resources created by the object, not the object itself, which is destroyed by the garbage collection mechanism.

When we create multiple objects in a file, when the file is executed and the objects are destroyed, the objects created first are destroyed first, and the objects created later are destroyed first. This The principle and the principle of stack are very similar, first in, last out, last in, first out.

Summary

Through the above explanation of classes and objects, we can know the differences and connections between classes and objects. Classes are abstract and represent a type of thing, such as cats. Objects are concrete and represent a specific thing. A class is a template for an object, and an object is an instance of a class. At the same time, the basic composition of the class must be mastered.

The above is the content of PHP basic tutorial nine and objects. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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!