Table of Contents
Summary of PHP object-oriented essentials
Home Backend Development PHP Tutorial Summary of PHP object-oriented essentials_PHP tutorial

Summary of PHP object-oriented essentials_PHP tutorial

Jul 13, 2016 am 10:14 AM
extends php use accomplish object Summarize inherit Overload For magic

Summary of PHP object-oriented essentials

1 Use extends to implement inheritance, overloading, and the meaning of magic methods

class B extends A
When declaring, B does not need to have the method in A
When calling:

$b=new B();
$b->Method() in A;
$b->Attributes in A=1;
$b->Method() in B;
$b->Method() in B;

If $a=new A();
Yes
$a->Method() in A;
$a->Attributes in A=1;
Not possible
$a->Method() in B;
$a->Method() in B;

Overloading: B inherits A, and B implements the method attribute with the same name as A.
"Overloading" in PHP is different from most other object-oriented languages. Traditional "overloading" is used to provide multiple class methods with the same name, but each method has different parameter types and numbers.

Magic methods: PHP treats all class methods starting with __ (two underscores) as magic methods. So when you define your own class methods, do not prefix them with __.

2 Inherit the visibility of private and protected access modifiers

Attribute methods private cannot be inherited
The attribute method protected class is not visible outside and can be inherited
Class members defined by public property methods can be accessed from anywhere

3 Application of double colon:: in php

The "::" operator is often seen in PHP class code. This is a scope limiting operator, which is represented by a double colon "::". It is used to set the level of different scopes in the class. The left side is the scope and the right side is the members of the access scope.
There are two scopes defined in PHP: self and parent (static scope is provided in PHP6).

The scope resolution operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static members, methods and constants and can also be used by subclasses to override members and methods in parent classes.

The code is as follows:

class MyClass {
const CONST_VALUE = 'A constant value';
}

echo MyClass::CONST_VALUE;
class OtherClass extends MyClass
{
Public static $my_static = 'static var';

public static function doubleColon() {
echo parent::CONST_VALUE . "n";
echo self::$my_static . "n";
}
}

OtherClass::doubleColon();
//Subclass overrides parent class
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()n";
}
}

class OtherClass extends MyClass
{
// Override the method in the parent class
Public function myFunc()
{
​​​​ //But the overridden method can still be called
        parent::myFunc();
           echo "OtherClass::myFunc()n";
}
}

$class = new OtherClass();
$class->myFunc();

4 The role of this, self and parent in php

this: is a pointer to the current object instance, not to any other object or class.
self: represents the scope of the current class. Unlike this, it does not represent a specific instance of the class. Self cannot be used in code outside the class, and it cannot identify its own position in the hierarchy of inheritance. That is to say, when self is used in an extended class, it does not call the method of the parent class, but the overloaded method of the extended class. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self is used to point to static variables in the class.

. The code is as follows:

private static $firstCount = 0;
private $lastCount;

//Constructor
function __construct()
{
$this->lastCount = ++self:$firstCount; //Use self to call static variables. When calling self, you must use:: (field operation symbol)
}


parent: Indicates the scope of the parent class of the current class, and the rest is the same as the self attribute. parent is a pointer to the parent class. Generally, we use parent to call the constructor of the parent class.

The code is as follows:

//Constructor of inherited class
function __construct( $personSex, $personAge )
{
​​​​​ parent::__construct( "test" ); //Use parent to call the constructor of the parent class
            $this->personSex = $personSex;
             $this->personAge = $personAge;
}

5 Constructor and Destructor

A class with a constructor will call this method first every time an object is created, so it is very suitable to do some initialization work before using the object.
function __construct() {}
If a constructor is defined in a subclass, the constructor of its parent class will not be implicitly called. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.
PHP 5 introduced the concept of destructors, similar to other object-oriented languages ​​such as C++. A destructor is executed when all references to an object are removed or when the object is explicitly destroyed.
function __destruct() {}

6 final keyword

PHP 5 adds a new final keyword. If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final, it cannot be inherited.

7 Inheritance and Constructor

父类 子类 结果
有构造函数 无构造函数 父构造
有构造函数 有构造函数 子构造



8 Interface

You can define an interface through interface, just like defining a standard class.
Note:
1) But all the methods defined in it are empty;
2) All methods defined in the interface must be public, which is a characteristic of the interface;
3) When implementing multiple interfaces, methods in the interfaces cannot have duplicate names;
4) Interfaces can also be inherited by using the extends operator;
5) Constants can also be defined in the interface. Interface constants and class constants are used exactly the same. They are all fixed values ​​and cannot be modified by subclasses or subinterfaces.

//Declare an 'iTemplate' interface

interface iTemplate
{
Public function setVariable($name, $var);
Public function getHtml($template);
}
// Implement interface
// The following writing is correct
class Template implements iTemplate
{
Private $vars = array();

Public function setVariable($name, $var)
{
            $this->vars[$name] = $var;
}

Public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

          return $template;
}
}

9 attributes

The variable members of the class are called "properties". The property declaration starts with the keywords public or protected or private, and is followed by a variable. The variables in the attributes can be initialized, but the initialized value must be a constant. The constant here refers to the constant that the PHP script is in the compilation stage, not the constant calculated in the running stage after the compilation stage.
In PHP5, two functions "__get()" and "__set()" are predefined to obtain
Get and assign its attributes, as well as "__isset()" to check attributes and "__unset()" to delete attributes.
To put it simply, one is for obtaining value and the other is for assigning value. , the two methods "__set()" and "__get()", these two methods do not exist by default, but are manually added to the class. Like the constructor method (__construct()), they are added to the class. will exist. You can add these two methods in the following way. Of course, you can also add them according to your personal style: //__get() method is used to obtain private attributes

The code is as follows:

class Person{
//The following are the member attributes of people
private $name; //Person’s name
private $sex; //person’s gender
private $age; //Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);}else {
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete private members
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name))."
";
echo $p1->name."
";
//When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

The code is as follows:

class Person{
//The following are the member attributes of people
private $name;
//Person’s name
private $sex;
//Person’s gender
private $age;
//Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);
}else{
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete a private member
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name))."
";
echo $p1->name."
";
//When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

10 clones

Object copying can be completed through the clone keyword (if the __clone() method exists in the object, it will be called first). The __clone() method in an object cannot be called directly.
When an object is copied, PHP5 will perform a "shallow copy" of all properties of the object. All references in the properties remain unchanged and point to the original variables. If the __clone() method is defined, the __clone() method in the newly created object (the object generated by copying) will be called and can be used to modify the value of the attribute (if necessary).

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907713.htmlTechArticlePHP object-oriented summary 1 Use extends to implement inheritance, overloading, and the meaning of magic methods class B extends A declaration When there is no method in A in B, when calling: $b=new...
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,

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

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

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