Home  >  Article  >  Backend Development  >  Object Orientation in PHP

Object Orientation in PHP

WBOY
WBOYOriginal
2016-07-30 13:30:021036browse

Access control (visibility)

PHP’s access control includes public, protected and private

Class members defined as public can be accessed anywhere.
Class members defined as protected can be accessed by itself and its subclasses and parent classes.
Class members defined as private can only be accessed by the class in which they are defined.

cannot be used to modify class

Class attributes cannot be omitted and must be defined as one of public, protected, and private.

If these keywords are not set for a method in a class, the method will be public by default.

Objects of the same class can access each other's private and protected members even if they are not the same instance. This is because the internal implementation details of these objects are known.


Property

Use -> (object operator): $this->property (where property is the name of the property) to access non-static properties. Static properties are accessed using :: (double colon): self::$property.

$this is a reference to the calling object.


Class constants

can always remain unchanged in the class. Values ​​are defined as constants. There is no need to use the $ symbol when defining and using constants

The value of a constant must be a fixed value, not a variable, class attribute, the result of a mathematical operation or a function call

Use double colon:: to access

<code>const constant = 'constant value';
</code>

automatically Loading classes

Many developers create a PHP source file for each class definition when writing object-oriented applications. A big annoyance is having to write a long list of include files (one file per class) at the beginning of each script.

In PHP 5, this is no longer necessary. You can define a spl_autoload_register() function that will be automatically called when trying to use a class that has not been defined yet. By calling this function, the scripting engine has a last chance to load the required classes before PHP fails with an error.

<code><?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// 或者,自 PHP 5.3.0 起可以使用一个匿名函数
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

?>
</code>

Constructors and Destructors

Constructors and destructors are not called secretly by the engine. To execute the constructor and destructor of the parent class, you must explicitly call parent::__construct(); parent::__destruct()


inherit

in the constructor body and destructor body of the child class

Unless autoloading is used, a class must be defined before use. If one class extends another, the parent class must be declared before the child class. This rule applies to classes inheriting other classes and interfaces.

Inheritance uses the extends keyword


Scope parsing operator (::)

The range parsing operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static Members, class constants


Static (static) keyword

declares class attributes or methods as static, so they can be accessed directly without instantiating the class. Static properties cannot be accessed through an object of a class that has been instantiated (but static methods can).

Static properties and methods are public by default


Abstract class

Use the keyword abstract

Any class, if at least one method in it is declared as abstract, then this class must be declared as Abstract.

A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation.

When inheriting an abstract class, the subclass must define all abstract methods in the parent class; in addition, the access control of these methods must be the same as that in the parent class (or more relaxed)


Interface

Interface is through interface Keyword

All methods defined in the interface must be public. This is a characteristic of the interface. Constants can also be defined in the interface. The use of interface constants and class constants are exactly the same, but they cannot be overridden by subclasses or subinterfaces. To implement an interface, use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces. Use commas to separate the names of multiple interfaces.

Interfaces can also inherit interfaces

Traits

Since PHP 5.4.0, PHP has implemented a method of code reuse called traits.
<code><?php
trait ezcReflectionReturnInfo {
    function getReturnType() { /*1*/ }
    function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use ezcReflectionReturnInfo;
    /* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
    use ezcReflectionReturnInfo;
    /* ... */
}
?>
</code>

List multiple traits in the use statement separated by commas

<code><?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}
?>
</code>

Magic method

__construct()
__destruct()

__call()

__callStatic()

__get()
__set()
__isset()
__unset()
The __sleep() serialize() function checks whether a magic method __sleep() exists in the class. If present, this method will be called first, and then the serialization operation will be performed.
__wakeup() unserialize() checks whether there is a __wakeup() method. If it exists, the __wakeup method will be called first
__toString() is used to describe how a class should respond when it is treated as a string
__invoke() When trying to call an object by calling a function, the __invoke() method is automatically called
__set_state() This static method will be called when var_export() is called to export the class
__clone()
__debugInfo() var_dump() is called when an object is used

These functions are called "Magic methods" in PHP. You cannot use these method names when naming your own class methods unless you want to use their magic functionality.

When assigning a value to an inaccessible property, __set() will be called.

When reading the value of an inaccessible property, __get() will be called.

__isset() is called when isset() or empty() is called on an inaccessible property.

When unset() is called on an inaccessible property, __unset() will be called.

When calling an inaccessible method in an object, __call() will be called.

When calling an inaccessible method in static mode, __callStatic() will be called.


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.

Properties cannot be defined as final, only classes and methods can be defined as final


Object copying

Object copying can be done through the clone keyword (this will call the object's __clone() method if possible). The __clone() method in an object cannot be called directly.


Object comparison

When using the comparison operator (==) to compare two object variables, the comparison principle is: if the attributes and attribute values ​​of the two objects are equal, and the two objects are instances of the same class , then the two object variables are equal.

If you use the equality operator (===), these two object variables must point to the same instance of a certain class (that is, the same object).


Type constraints

PHP 5 can use type constraints. Function parameters can be specified to be objects (specify the class name in the function prototype), interfaces, arrays (from PHP 5.1) or callable (from PHP 5.4). However, if you use NULL as the default value of the parameter, you can still use NULL as the actual parameter when calling the function.

Type constraints cannot be used for scalar types such as int or string. Traits are not allowed either.

Type constraints are not only used in class member functions, but can also be used in functions


Object serialization

All values ​​in PHP can use the function serialize() to return a string containing a byte stream To represent. The unserialize() function can change the string back to the original value of PHP. Serializing an object will save all the object's variables, but not the object's methods.


Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above has introduced object-oriented in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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