Home  >  Article  >  Backend Development  >  Summarize the basics of PHP objects

Summarize the basics of PHP objects

WBOY
WBOYforward
2022-03-09 18:11:595377browse

This article brings you relevant knowledge about PHP, which mainly introduces object-oriented related issues. The essence of object-oriented programming is to increase the operating subjects of data and functions, that is, objects. I hope everyone has to help.

Summarize the basics of PHP objects

Recommended study: "PHP Tutorial"

Practical learning of php, thinkphp, Redis, vue, uni-app and other technologies, Recommended open source e-commerce system likeshop, you can learn from ideas, you can go to copyright for free commercial use, gitee download address:
Click to enter the project address

Object-oriented: OOP (objected oriented programming) programming

Process-oriented is a programming idea

The essence of object-oriented programming is to increase the operating subject of data and functions, that is, objects

All data and functions in object-oriented are mostly composed of subjects (objects ) to call and operate

Object-oriented basics

The difference between process-oriented and object-oriented

Summarize the basics of PHP objects

Object-oriented keywords

  • Class: class, defines the outermost structure of the object-oriented subject, used to wrap the subject's data and functions (functions)
  • Object: object, a specific representative of a certain type of transaction, also called an instance
  • Instantiation: new, the process of generating objects from a class
  • Class member: member
    • Method: method, which is essentially a function created in the class structure, called Member method or member function
    • Attribute: property, essentially a variable created in the class structure, called a member variable
    • Class constant: const, essentially created in the class structure Constants

Create objects

<?phpclass  People{}$man=new People();# 实例化类,man就是对象var_dump($man);?>
    # 输出object(People)#1 (0) { }
    #1表示:对象编号,与类无关,是整个脚本中对象的序号(0)表示:成员变量(属性)个数{}表示:具体成员变量信息(键值对)

Class objects

<?phpclass  Buyer{
    # 常量声明
    const BIG_NAME=&#39;BUYER&#39;;
    # 常量不需要加 $

    # 属性声明
    # $name;
    # 错误的,类内部属性必须使用访问修饰限定符
    public $name;
    public $money=0;
    
    # 方法声明
    function display(){
        echo __CLASS__;
        # 魔术常量,输出类名
        # 方法内部变量属于局部变量
    }}# 实例化$a = new Buyer();# 属性操作,增删改查echo $a->money;$a->money='20';$a->sex='male';unset($a->name);echo '<br>';# 方法操作$a->display();echo '<br>';var_dump($a);?>
    # 输出0Buyerobject(Buyer)#1 (2) { ["money"]=> string(2) "20" ["sex"]=> string(4) "male" }

Note: Class constants are not accessed by objects

Access modification qualifier

Modification keyword before a property or method, used to control the access location of the property or method

  • public: public, both inside and outside the class Access
  • protected: protected, only allowed to be accessed within the relevant class
  • private: private, only allowed to be accessed within the defining class

Attributes must have access modifications Qualifier, the method can have no access modification qualifier, the default is public

internal object of the class

$this, an object built into the method, will automatically point to the object of the method being called

$this exists inside the method (for internal use only), so it is equivalent to being inside the structure of the class

  • You can access any member modified by the access modification qualifier
  • Private members are accessed through public methods (public methods can be accessed outside the class)
<?phpclass  Article{
    protected $name = &#39;a&#39;;
    private $type = &#39;art&#39;;

    public function get_name()
    {
        var_dump($this);
    }}$a = new Article();var_dump($a);?>
    # 输出object(Article)#1 (2) { ["name:protected"]=> string(1) "a" ["type:private"]=> string(3) "art" }

$this represents the object, and the environment where $this is located is inside the method inside the class, so $ The this object is accessed within the class, so all properties and methods are not restricted by access modification qualifiers

Summarize the basics of PHP objects

Summarize the basics of PHP objects

Summarize the basics of PHP objects

##Construction method

  • __construct() is a system-built-in magic method. The characteristic of this method is that the object automatically calls it immediately after the object is instantiated

  • The purpose of the constructor is to initialize resources, including object properties and other resources

  • Once the constructor is defined and the constructor comes with its own parameters, then You can only use the new class name (parameter list) method to instantiate it correctly

  • The magic method can also be called by direct calling from the object, but it is of no practical use

<?phpclass  Article{
    public $name=&#39;xiaoli&#39;;
    private $sex="male";

    public function __construct($name,$sex)
    {
        $this->name = $name;
        $this->sex = $sex;
    }}$a = new Article('xiaowang', 'famale');var_dump($a);?>
Destructor method

    __destruct(), automatically called when the object is destroyed, releases resources
  • Object destruction
    1. Object has no variables Pointing (variable points to other data)
    2. The object is actively destroyed (unset destroys the object variable)
    3. Script execution ends (automatically releases resources)
  • PHP When the script is executed, all resources will be released, so the destructor method is generally less used
<?phpclass  Article{
    protected $name = &#39;xiaoli&#39;;
    private $sex = &#39;famale&#39;;

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        echo __FUNCTION__;
    }}$a=new Article();# 销毁对象$a=1;unset($a);# __destructendecho &#39;end&#39;;?>
    # 不销毁对象,php在运行结束也会释放资源# end__destruct
Object passing value

Definition: Assign the variable holding the object to another variable

In PHP, the value of an object is passed by reference: that is, one object variable is assigned to another variable, and the two variables point to the same object address, that is, there is only one object.

<?phpclass  Article{
    public $name = &#39;xiaoli&#39;;
    public $sex = &#39;famale&#39;;}$a=new Article();$b=$a;var_dump($a,$b);echo &#39;<br>';$a->name="wangxiaohu";var_dump($a,$b);echo '<br>';?>
    # 输出object(Article)#1 (2) { ["name"]=> string(6) "xiaoli" ["sex"]=> string(6) "famale" } object(Article)
    #1 (2) { ["name"]=> string(6) "xiaoli" ["sex"]=> string(6) "famale" }object(Article)
    #1 (2) { ["name"]=> string(10) "wangxiaohu" ["sex"]=> string(6) "famale" } object(Article)
    #1 (2) { ["name"]=> string(10) "wangxiaohu" ["sex"]=> string(6) "famale" }
Range resolution operator ( Class constant access)

There are two colons forming "::", which is specially used for

classes to implement class member operations, and the class can directly access class members

  • The scope resolution operator is used to access class members for a class (class name)

    类名::类成员
  • The range resolution operator can also be used by objects as classes ( Not recommended)

    $对象名::类成员
  • Class constants can only be accessed by classes

<?phpclass  Article{
    const  NAME=&#39;ocean&#39;;}echo Article::NAME;
    # 常量是不能通过 Article->NAME 来进行访问的$a=new Article();echo $a::NAME;
    # 范围解析操作符兼容对象,找到对象所属类最终进行访问,效率降低,灵活性提高?>
Class constants are fixed, while the properties of objects are different for different objects. of

Summarize the basics of PHP objects

静态成员

定义:使用 static 关键字修饰的类成员,表示该成员属于类访问

  • 静态成员
    • 静态属性
    • 静态方法
  • 静态成员是明确用来给类访问的,而不是对象
  • 静态成员只是多了一个 static 关键字修饰,本身也可以被对象访问
  • 静态成员同样可以使用不同的访问修饰限定符限定,效果一致

Summarize the basics of PHP objects

<?phpclass  Article{
    public static $name = &#39;hlm&#39;;
    public static $type = &#39;art&#39;;

    public static function getName()
    {
        return self::$name;
    }}# 静态属性$a = new Article();echo Article::$name;# 静态方法echo Article::getName();?>

self关键字

  • 在类的内部(方法里面)使用,代替类名的写法
  • self 如同 $this 代表内部对象一样,能够在方法内部代替当前类名
  • 能够保障用户方便修改类名字
  • self 关键字是代替类名,所以需要配合范围解析操作符 ::
<?phpclass  Article{
    public static function getInstance1()
    {
        return new self();
    }

    public static function getInstance2()
    {
        return new Article();
    }}$a = Article::getInstance1();$b = Article::getInstance2();var_dump($a,$b);?>
    # 输出object(Article)
    #1 (0) { } object(Article)
    #2 (0) { }

类加载

类的访问必须保证类在内存中已经存在,所以需要再用类之前将类所在的 PHP 文件加载到内存中

  • 类的加载分为两种

    • 手动加载:在需要使用类之间通过 include 将包含类的文件引入到内存
    • 自动加载:提前定义好类结构和位置,写好引入类文件代码,在系统需要类而内存不存在的时候想办法让写好的加载类的代码执行(自动加载是自动运行写好的加载类的代码)
  • 自动加载两种方式

    • 魔术函数 __autoload:系统自动调用,需要传入类名,在函数内部实现类的手动加载(PHP7及之后不建议使用此方法)
    function __autoload($classname){
        # 找到对应的文件路径和命名规范,手动加载}
     
    • 自定义函数:自己定义类的加载实现,然后通过 spl_autoload_register 注册到自动加载机制(可注册多个自动加载)
    # 自定义类加载函数function 自定义函数($classname){
        # 找到对应的文件和命名规范,手动加载}#注册自动加载sql_autoload_register('自定义函数名字')

自动加载要求在声明类的时候有良好的规范

  • 类名与文件名一致:类名.php 或者 类名.class.php
  • 类文件分类放好

Summarize the basics of PHP objects

例:手动加载

Summarize the basics of PHP objects

Article.php

<?phpclass  Article{
    public function getName(){
        return __METHOD__;
    }}

mian.php

<?php # include &#39;Article.php&#39;;# 直接加载比较消耗资源,而且如果类已经在内存中存在,直接include会报错,建议判断后再加载if(!class_exists(&#39;Article&#39;)){
    include &#39;Article.php&#39;;}$a=new Article();var_dump($a->getName());
    # outputstring(16) "Article::getName"

自动加载

  • __autoload(不建议使用)

一个系统中,可能类文件会放到不同的路径下,因此一个完整的自动加载函数,应该要进行文件判定功能

<?php function __autoload($classname){
    # 形参代指 类名
    #组织文件路径,假设当前路径下,有两个文件夹下都有类c和类m
    $c_file = &#39;c/&#39; . $classname . &#39;.php&#39;;
    if (file_exists($c_file)) {
        include_once($c_file);
        return true;
    } 
    //if 语句如果只有一行不需要加 {}
    //include_once 只加载一次

    $m_file = &#39;m/&#39; . $classname . &#39;.php&#39;;
    if (file_exists($m_file)) {
        include_once($m_file);
        return true;
    }
}


$a=new Article();
$b=new Article();
  • spl_autoload_register
<?phpfunction  autoload01($classname){
    if(!class_exists($classname)){
        $file_name=$classname.&#39;.php&#39;;
        if(file_exists($file_name)) include_once $file_name;
    }}spl_autoload_register(&#39;autoload01&#39;);$a=new Article();

对象克隆

通过已有的对象复制一个新的同样的对象,但两者之间并非同一个对象

Summarize the basics of PHP objects

Summarize the basics of PHP objects

面向对象高级

面向对象三大特性

封装、继承、多态

类的封装

Summarize the basics of PHP objects

类的继承

inherit,子类合法拥有父类的某些权限

  • 继承必须满足继承关系:即存在合理的包含关系
  • 继承的本质是子类通过继承可以直接使用父类已经存在的数据和数据操作
  • PHP 使用 extends 关键字表示继承

子类也称派生类

父类也称基类

# 父类class Human{}# 子类继承class Man extends Human{}

类的多态

多态性是指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果

  • 需要发生类的继承,同时出现方法的重写(override),即子类拥有与父类同名的方法
  • 在实例化对象的时候让父类对象指向子类对象(强制类型,PHP不支持,PHP 弱类型很灵活)
  • 结果:父类对象表现的子类对象的特点

Summarize the basics of PHP objects

—PHP继承—

<?phpclass  Human{
    public function show(){
        echo __METHOD__;
    }}class Man extends Human{}$m=new Man;$m->show();

有限继承

子类在继承父类的成员时,并非继承所有内容,而是继承并使用父类部分内容

  • The essence of inheritance in PHP is object inheritance
  • Inherited content in PHP: all public members, protected members and private properties of the parent class, private methods cannot be inherited
  • Protected members are exclusively for inheritance and can be accessed within the parent class or subclass.
  • Private members can only be accessed by setting public or protected methods in the class to which they belong
  • Construction Methods and destructor methods can be inherited by subclasses,

override Override

override, subclasses define members with the same name as the parent class

Summarize the basics of PHP objects

parent keyword

An expression to explicitly access the members of the parent class

Summarize the basics of PHP objects

After the method is overridden, access the called It is a subclass method. If you want to access the parent class method, you can force access to the parent class method by using parent in the subclass method

parent cannot be used to access the properties of the parent class (static properties can)

PHP Inheritance Features

  • PHP can only inherit single, there is only one parent class (if you inherit multiple classes, you can use chain inheritance)
  • In PHP inheritance, there is only Private methods cannot be inherited
  • PHP allows inheritance of the constructor and destructor methods in the parent class

Static delayed binding

Summarize the basics of PHP objects

Summarize the basics of PHP objects

##Final class Final

Use the final keyword to modify the class name, indicating that this class cannot be inherited

The final keyword can also modify methods, indicating methods Cannot be overridden (usually the class will not use the final keyword at this time)

Summarize the basics of PHP objects

Abstract class Abstract

A class modified with the abstract keyword, indicating that the Classes can only be inherited and cannot be instantiated

abstract keyword can modify the method, indicating that the method is an abstract method. Abstract methods have no method body (no {})

Classes with abstract methods Must be an abstract class

The class that inherits the abstract class must either be an abstract class or implement all the abstract methods in the abstract class

trait code reuse

Summarize the basics of PHP objects

Applicable to situations where there is common code between different classes, but there is no inheritance relationship between the classes. In this case, the common code can be stored in the trait.

The trait can have internal members that can be owned by a class. Properties (including static), member methods (including static and abstract methods), but cannot have class constants

trait is used for code reuse, cannot be instantiated, cannot be inherited

trait has the same name

A class may need to introduce multiple traits, and the same name may appear in different traits

Summarize the basics of PHP objects

Interface

Interface, specially used Standardize the methods that some common classes must implement

    The interface is not a class, but it has a similar structure to the class
  • The interface cannot be instantiated, but the class can implement the interface
interface interface name{}

class class nameimplements interface name{}

Summarize the basics of PHP objects

Interface members

Interface members can only have two types

    Interface constants: const
  • Common interface methods (ordinary methods and static methods)

Summarize the basics of PHP objects

PHP overload

overload means that multiple methods with the same name can appear in a class, and the number and type of parameters are different from each other

Summarize the basics of PHP objects

Used for fault tolerance

Attribute overloading

When the object accesses properties that do not exist or have insufficient permissions, the magic method is automatically triggered so that the code does not go wrong.

Attribute overloading magic method

    __get(attribute name): Triggered when accessing an attribute that does not exist or has insufficient permissions
  • __set(attribute name, attribute value) : Triggered when setting attributes that do not exist or have insufficient permissions
  • __isset(attribute name): Triggered when determining attributes that do not exist or have insufficient permissions
  • __unset(attribute name): Delete non-existence or permissions Triggered when there are insufficient attributes
  • __tostring(): treated as a string

method overload

object or class access does not exist or Methods with insufficient permissions, automatically triggered magic methods to make the code error-free

  • __cal(方法名,方法参数列表):调用不存在或者权限不够的方法时触发
  • __callStatic(方法名,方法参数列表):调用不存在或者权限不够的静态方法时触发

对象遍历

将对象中的所有属性以键值对的形式取出并进行访问

  • 对象是一种复合数据类型,对象中真正保存的内容是属性

  • 对象的属性本质也是一种键值对关系:名字 = 值

  • 对象遍历就是利用 foreach 对对象中的属性进行取出解析

  • 对象遍历遵循访问修饰限定符的限定:即类外只能遍历所有共有属性

    foreach(对象变量 as [属性名变量 =>] 属性值变量){
        #属性名变量代表取出的每个属性的名字
        #属性值变量代表取出的每个属性的值}

    Summarize the basics of PHP objects

Iterator 迭代器

Summarize the basics of PHP objects

生成器

Summarize the basics of PHP objects

Summarize the basics of PHP objects

yield 关键字

设计模式

design pattern,是软件开发人员在软件开发过程中问题的解决方法

单例模式

singleton,是一种类的设计只会最多产生一个对象的设计思想Summarize the basics of PHP objects

保证资源唯一性

工厂模式

。。。。。。

命名空间

namespace,指人为的将内存进行分隔,让不同内存区域的同名结构共存,从而解决在大型项目能出现重名结构问题

Summarize the basics of PHP objects

基础语法:

namespace 关键字定义空间

命名规则

字母、数字、下划线,不能以数字开头

命名空间必须写在所有代码之前,定义了一个,之后可以定义多个

Summarize the basics of PHP objects

子空间

subspace,即在已有空间之上,再在内部进行空间划分

子空间直接通过 namespace+路径符号 \ 实现

非限定名称

直接访问元素本身,代表当前所属空间(当前目录)

限定名称

使用空间名+原名,代表访问当前空间子空间(当前目录子目录)

完全限定名称

从根目录(全局空间)开始访问,使用 \ 作为全局空间开始符号(根目录)

全局空间元素访问:使用完全限定名称访问

Summarize the basics of PHP objects

命名空间引入

Summarize the basics of PHP objects

推荐学习:《PHP视频教程

The above is the detailed content of Summarize the basics of PHP objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete