Table of Contents
Directory
1. Classes and objects
2. Automatic loading Object:
3. Constructor and destructor
Access Control" >4 .Access Control
5 .对象继承
6 .范围解析操作符(::)
Home Backend Development PHP Tutorial Comprehensive understanding of PHP classes and objects

Comprehensive understanding of PHP classes and objects

Jun 28, 2017 pm 01:50 PM
php

Directory

PHP Classes and objects Full analysis (1)

Full analysis of PHP classes and objects (2)

PHP classes and objects Full analysis (3)

1. Classes and objects

Object: The individual entity of each physical object that actually exists in this type of thing. $a =new User(); The instantiated $a
reference: php alias, two different variable names point to the same content

Encapsulation: properties and methods of the objectOrganized in a class (logical unit)
Inheritance: Create a new class based on the original class for the purpose of code reuse;
Polymorphism: Allows pointer assignment of subclass types Pointer to parent type.
---------------------------------------------

2. Automatic loading Object:

Auto-loading defines a special autoload function. This function will be automatically called when a class that is not defined in the script is referenced.

[php] view plaincopyprint?
 function autoload($class){
   require_once("classes/$class.class.php");
 }
Copy after login

Why use autoload

1, first of all, I don’t know where this class file is stored,
2, and the other is that I don’t know when this file needs to be used.
3, especially when there are a lot of project files, it is impossible to write a long list of require at the beginning of each file...

replaces a
require_once ("classes/Books.class .php") ;
require_once ("classes/Employees.class.php" ) ;
require_once ("classes/Events.class.php") ;
require_once ("classes/Patrons.class.php ") ;

zend recommends one of the most popular methods, including the path in the file name. For example, in the following example:

[php] view plaincopyprint?

    view sourceprint?  
    // Main.class    
      
    function autoload($class_name) {     
         $path = str_replace('_', DIRECTORY_SEPARATOR, $class_name);     
         require_once $path.'.php';     
     }
Copy after login

temp = new Main_Super_Class();

All underscores will be replaced with separators in the path. In the above example, it will go to Main/Super/Class. php file.

Disadvantages:

is that during the coding process, you must clearly know where the code file should be,

And because the file path is hard-coded in the class name , if we need to modify the folder structure, we must manually modify all class names.

If you are in a development environment and don't care much about speed, it is very convenient to use the 'Include All' method.
By placing all class files in one or several specific folders, and then finding and loading them through traversal.
For example

   <?php     
      
    $arr = array (     
         &#39;Project/Classes&#39;,     
        &#39;Project/Classes/Children&#39;,     
        &#39;Project/Interfaces&#39;    
     );    
      
     foreach($arr as $dir) {     
      
        $dir_list = opendir($dir);    
      
        while ($file = readdir($dir_list)) {     
             $path = $dir.DIRECTORY_SEPARATOR.$file;     
             if(in_array($file, array(&#39;.&#39;, &#39;..&#39;)) || is_dir($path))     
                 continue;    
             if (strpos($file, ".class.php"))     
                 require_once $path;     
         }     
    }     
      
     ?>
Copy after login

Another method is to establish an association between the class file and its location Configuration file, for example:

    view sourceprint?  
    // configuration.php           
    array_of_associations = array(     
        &#39;MainSuperClass&#39; = &#39;C:/Main/Super/Class.php&#39;,     
        &#39;MainPoorClass&#39; = &#39;C:/blablabla/gy.php&#39;    
     );
Copy after login

Called file

    <?php     
        require &#39;autoload_generated.php&#39;;    
        function autoload($className) {     
           global $autoload_list;     
           require_once $autoload_list[$className];     
        }    
          $x = new A();     
    ?>
Copy after login

--------------------------------------------- ---

3. Constructor and destructor

PHP Construction method construct() allows the constructor method to be executed before instantiating a class.

The constructor is a special method in the class. When an instance of a class is created using the new operator, the constructor method is automatically called and its name must be construct() .

(Only one constructor can be declared in a class, but the constructor will only be called once every time creates an object. This method cannot be called actively,
So it is usually used to perform some useful initialization tasks. This method has no return value. )

Function: Used to initialize the object when creating the object
The subclass executes the classified constructor parent::construct(). .

Destructor: destruct () definition: a special internal member function with no return type, no parameters, cannot be called at will, and is not overloaded;
only when the life of the class object ends, The resources allocated in the constructor are automatically called by the system to release.

Corresponding to the constructor method is the destructor method. The destructor method allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc.
The destructor cannot take any parameters, and its name must be destruct().
Effect: Clean up the aftermath work. For example, use new to open up a memory space when creating an object. The destructor should be used to release the resources allocated in the constructor before exiting.

Example:

    class Person {  
        public $name;  
        public $age;  
      
        //定义一个构造方法初始化赋值  
        public function construct($name,$age) {  
            $this->name=$name;  
            $this->age=$age;  
        }  
        public function say() {  
            echo "my name is :".$this->name."<br />";  
            echo "my age is :".$this->age;  
        }  
        //析构函数  
        function destruct()  
        {  
            echo "goodbye :".$this->name;  
        }  
    }  
      
    $p1=new Person("ren", 25);  
    $p1->say();
Copy after login

---------------------------------- ----------------------------

4 .Access Control

Access control to properties or methods is achieved by adding the keywords public, protected or private in front
Class members defined by public can be accessed from anywhere;
Class members defined by protected can be accessed from anywhere Accessible by subclasses and parent classes of the class in which it is located (of course, the class in which the member is located can also be accessed);
Class members defined as private can only be accessed by the class in which they are located.
Access control of class members
Class members must be defined using the keywords public, protected or private

Access control of methods
Methods in the class must use the keyword public , protected or private to define. If these keywords are not set, the method will be set to the default public.

example:

class MyClass  
{  
    public $public = &#39;Public&#39;;  
    protected $protected = &#39;Protected&#39;;  
    private $private = &#39;Private&#39;;  
  
    function printHello()  
    {  
        echo $this->public;  
        echo $this->protected;  
        echo $this->private;  
    }  
}  
  
$obj = new MyClass();  
echo $obj->public; // 这行能被正常执行  
echo $obj->protected; // 这行会产生一个致命错误  
echo $obj->private; // 这行也会产生一个致命错误  
$obj->printHello(); // 输出 Public、Protected 和 Private
Copy after login

-------------------------------------------------------------

5 .对象继承

继承定义:以原有的类为基础,创建一个新类,从而代码复用的目的;
--------------------------------------
覆写是对象继承时用到的
重载是单对象中同方法名不同参数的方法
--------------------------------------

继承已为大家所熟知的一个程序设计特性,PHP 的对象模型也使用了继承。继承将会影响到类与类,对象与对象之间的关系。

比如,当扩展一个类,子类就会继承父类的所有公有和保护方法。但是子类的方法会覆盖父类的方法。

继承对于功能的设计和抽象是非常有用的,而且对于类似的对象增加新功能就无须重新再写这些公用的功能。

    class Person {  
        public $name;  
        public $age;  
      
        function say() {  
            echo "my name is:".$this->name."<br />";  
        echo "my age is:".$this->age;  
        }  
    }  
      
    // 类的继承  
    class Student extends Person {  
        var $school;    //学生所在学校的属性  
          
        function study() {  
            echo "my name is:".$this->name."<br />";  
            echo "my shool is:".$this->school;  
        }         
    }  
      
    $t1 = new Student();  
    $t1->name = "zhangsan";  
    $t1->school = "beijindaxue";  
    $t1->study();
Copy after login

------- --------- ------ --------- -------- -----

6 .范围解析操作符(::)

范围解析操作符(也可称作 Paamayim Nekudotayim)或者更简单地说是一对冒号,可以用于访问静态成员、方法和常量,还可以用于覆盖类中的成员和方法。
当在类的外部访问这些静态成员、方法和常量时,必须使用类的名字。

self 和 parent 这两个特殊的关键字是用于在类的内部对成员或方法进行访问的。
注意:
当一个子类覆盖其父类中的方法时,PHP 不会再执行父类中已被覆盖的方法,直到子类中调用这些方法为止

例子:

    <?php  
    class OtherClass extends MyClass  
    {  
        public static $my_static = &#39;static var&#39;;  
      
        public static function doubleColon() {  
            echo parent::CONST_VALUE . "\n";  
            echo self::$my_static . "\n";  
        }  
    }  
      
    OtherClass::doubleColon();  
    ?>
Copy after login

The above is the detailed content of Comprehensive understanding of PHP classes and objects. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles