Home > Backend Development > PHP Tutorial > Comprehensive understanding of PHP classes and objects

Comprehensive understanding of PHP classes and objects

怪我咯
Release: 2023-03-11 20:54:01
Original
1725 people have browsed it

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!

Related labels:
php
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