Object-oriented in PHP

Source: Internet
Author: User
Tags export class string back traits

Access Control (visibility)

PHP access control has public (publicly), protected (protected) and private (private)

Class members that are defined as public can be accessed from anywhere.
A class member that is defined as protected can be accessed by itself and its subclasses and parent classes.
A class member that is defined as private can only be accessed by the class in which it is defined.

cannot be used for retouchingclass

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

A method in a class is public by default if these keywords are not set.

Objects of the same class can access each other's private and protected members, even if they are not the same instance. This is due to the fact that the specifics of the implementation within these objects are known.

Property

The non-static property is accessed in such a way that the (object operator):$This->property (where property is the attribute name). Static properties are used with:: (double colon): Self::$property to access

$this is a reference to the calling object

Class constants

You can define a value that is always the same in a class as a constant. You do not need to use the $ symbol when defining and using constants

The value of a constant must be a fixed value, cannot be a variable, a class property, a result of a mathematical operation, or a function call

With double colons:: Access

const constant = ‘constant value‘;
Auto Load Class

Many developers write object-oriented applications to create a PHP source file for each class definition. A big annoyance is having to write a long list of included 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 called automatically when you try to use a class that is not already defined. By calling this function, the scripting engine has the last chance to load the required classes before PHP fails.

<?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‘;});?>
Constructors and destructors

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

Inherited

Unless automatic loading is used, a class must be defined before it is used. If one class extends another, the parent class must be declared before the child class. This rule applies to classes that inherit other classes and interfaces.

Inheritance using extends Keywords

Scope resolution operator (::)

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

static (statically) keyword

Declaring a class property or method as static can be accessed directly without instantiating the class. Static properties cannot be accessed through an object that a class has instantiated (but static methods can).

Static properties and methods default to Public

Abstract class

Use keywordsabstract

Any class, if at least one of its methods is declared abstract, then the class must be declared abstract.

A method that is defined as abstract simply declares its invocation method (parameter) and cannot define its specific function implementation.

When inheriting an abstract class, the subclass must define all the abstract methods in the parent class, and the access control for these methods must be the same as in the parent class (or more lenient)

Interface

Interface is through the interface keyword

All methods defined in the interface must be public, which is the attribute of the interface

Constants can also be defined in an interface. Interface constants and class constants are used exactly the same, but cannot be overridden by subclasses or sub-interfaces

To implement an interface, use the implements operator. All methods defined in the interface must be implemented in the class, or a fatal error will be reported. A class can implement multiple interfaces, separating the names of multiple interfaces with commas.

Interfaces can also inherit interfaces

Traits

Since PHP 5.4.0, PHP has implemented a method of code reuse, called traits.

<?phptrait ezcReflectionReturnInfo {    function getReturnType() { /*1*/ }    function getReturnDescription() { /*2*/ }}class ezcReflectionMethod extends ReflectionMethod {    use ezcReflectionReturnInfo;    /* ... */}class ezcReflectionFunction extends ReflectionFunction {    use ezcReflectionReturnInfo;    /* ... */}?>

Separated by commas, multiple trait are listed in the use Declaration

<?phptrait Hello {    public function sayHello() {        echo ‘Hello ‘;    }}trait World {    public function sayWorld() {        echo ‘World‘;    }}class MyHelloWorld {    use Hello, World;    public function sayExclamationMark() {        echo ‘!‘;    }}?>
Magic method

__construct ()
__destruct ()
__call ()
__callstatic ()
__get ()
__set ()
__isset ()
__unset ()
The __sleep () serialize () function checks to see if there is a magic method __sleep () in the class. If present, the method is called first before the serialization operation is performed.
__wakeup () unserialize () checks for the existence of a __wakeup () method. If present, the __wakeup method is called first
__tostring () How to respond when a class is treated as a string
__invoke () The __invoke () method is automatically called when an attempt is made to invoke an object in the same way as a function call
__set_state () This static method is called when the Var_export () export class is called
__clone ()
__debuginfo () Var_dump () an object when called

These functions are referred to in PHP as the "Magic Method" (Magic methods). You cannot use these method names when naming your own class methods, unless you want to use their magic features.

__set () is called when a value is assigned to an unreachable property.

__get () is called when the value of an inaccessible property is read.

When Isset () or empty () is called on an inaccessible property, __isset () is called.

When Unset () is called on an inaccessible property, __unset () is called.

When an inaccessible method is called in an object, __call () is called.

When a non-accessible method is called in a static manner, __callstatic () is called.

Final keyword

If a method in the parent class is declared final, the child class cannot overwrite the method. If a class is declared final, it cannot be inherited.

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

Object replication

Object replication can be done by using the Clone keyword (which, if possible, calls the object's __clone () method). The __clone () method in the object cannot be called directly.

Object comparison

When comparing two object variables with the comparison operator (= =), the principle of comparison is that if the properties and property values of the two objects are equal, and two objects are instances of the same class, the two object variables are equal.

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

Type constraints

PHP 5 can use type constraints. The parameters of the function can specify that the object must be (the name of the class specified in the function prototype), interface, Array (PHP 5.1), or callable (PHP 5.4). However, if you use NULL as the default value for the parameter, you can still use NULL as the argument when calling the function.

Type constraints cannot be used with scalar types such as int or string. Traits is not allowed.

Type constraints are not only used in member functions of a class, but also in functions

Serialization of objects

All values in PHP can be represented by using the function serialize () to return a string containing a stream of bytes. The Unserialize () function can re-change the string back to the original PHP value. Serializing an object will save all of the object's variables, but it will not save the object's methods.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Object-oriented in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.