search
HomeBackend DevelopmentPHP TutorialComprehensive understanding of PHP classes and objects

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");
 }

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';     
     }

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;     
         }     
    }     
      
     ?>

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;    
     );

Called file

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

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

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();

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

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

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

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();

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

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();  
    ?>

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
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor