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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles