PHP Object-oriented

Source: Internet
Author: User
Tags php class

Class

Declaration of the class:

<?php permission modifier class Name {   //permission Monk symbol: Public,protected,private or omit 3.        Class body; Class is a built-in keyword}//the category name must follow class, followed by {}.  The members of the class are placed between {}. ? >//ps: Before the class keyword, you can add a permission modifier, you can add static,abstract and other keywords. A class, that is, the entire contents of a pair of curly braces, is not allowed to split the contents of a class into pairs in a section of code. <?php Class conndb{//...?    ><? ...  };? >

Member Properties:

Variables that are declared directly in a class are called member properties/variables. The type can be scalar and composite types in PHP, and using resource types and empty types is not valid.

In addition, when declaring a member property, you must have a keyword to decorate: a keyword that has a specific meaning: public,protected,private; there is no need for a specific meaning: var. When declaring member properties, it is not necessary to assign an initial value.

Member constants:

Modified with const constants, for example: const PI = 3.1415926;

The output of the constant does not need to be instantiated, it is called directly from the class name + constant name, in the form: Class Name:: Constant Name

PS. Special access methods:--------"$this" and "::"

1) $ "This" exists in each member method, and it is a special object to use the method. The member method belongs to that object, and $this the application represents that object, its purpose is to specifically complete the access between the members of the object.

2) "::" becomes a scope operator, using this operator to invoke constants, variables, and methods in a class without creating an object. The syntax format is as follows:

Keyword:: variable name/constant name/method name

Keywords: parent, you can call member variables, member methods, and constants in the parent class member;

Self, you can call static members and constants in the current class;

The class name, which can invoke constants, variables, and methods in the class;

  

Member Methods:

A function declared in a class becomes a member method, in which multiple functions can be declared, that is, an object can have more than one member method. The declaration of a member method is the same as the declaration of a function, and the only special thing is that the member method can have a keyword that modifies it to control its access rights.

Instantiation of a class

To create an object:

$ Variable name = new class name ([parameter]); The instantiation of the class.

To access a class member:

$ variable Name, member property = value;

Construction method and destructor method

The constructor method is the method that the first chant object is automatically called after the object is created. It exists in the declaration of each class, and is a special member method, which is generally used to complete some initialization operations. If there is no construction method in the class, a constructor without parameters is automatically generated by default.

Format:

function _construct (formal parameter list) {//Method body};

The destructor method, in contrast to the construction method, is the last method called before the object is destroyed. It will complete a specific operation, such as closing the file and freeing the memory.

Format:

function _destruct () {//Method body};

Object-oriented features: encapsulation, abstraction, polymorphism.

Packaging:

Combines the member properties and methods in a class into a single, identical unit, and hides the contents of the object as much as possible. The purpose is to ensure that parts outside the class do not arbitrarily access the internal data of the class (member properties and member methods), thereby avoiding the impact of external errors on the internal data.

The encapsulation of a class is implemented by keyword Public,private,protected,static and final. The role of each keyword see PHP related documentation.

Inheritance:

Enables a class to inherit and have a member property and member method of another existing class, where the inherited class becomes the parent class and the inherited class becomes a subclass. Inheritance can improve the reusability and maintainability of code. The inheritance of the class is with the extends keyword.

Format:

Class subclass name extends the parent class name {//subclass method body. }

The parent:: keyword can also be used to call a member method in a subclass method, in the following format:

Parent:: The member method (parameter) of the parents class;

Methods that override the parent class:

The so-called method of overriding a parent class, that is, replacing a method inherited from a parent class with a method in a subclass, is also called a method override. The key to overriding is to create the same method in the subclass as the parent class, including the method name, parameter, and return type.

Polymorphism:

Polymorphism refers to the ability of a program to handle multiple types of objects. There are two implementations of PHP polymorphism, that is, through inheritance to achieve polymorphism and through the interface to achieve polymorphism.

Polymorphism is achieved through inheritance, that is, by overriding inherited member methods to achieve polymorphic effects.

  

<?php   abstract class parentclass{          abstract function printmessage ();        }    Class Subclassa extends parentclass{           function printmessage () {               echo "I am message from class A";           }    }    Class SUBCLASSB extends parentclass{           function printmessage () {               echo "I am message from class B";           }    }        function Printmsg ($object) {       if ($object instanceof parentclass) {           $object->printmessage ();       } else{            echo "error!";       }    }    $objectA =new Subclassa ();    Printmsg ($objectA);    $objectB =new SUBCLASSB ();    Printmsg ($objectB);? >   

Through the interface to achieve polymorphism, by defining interfaces, with empty methods. The class then inherits the interface.

<?php    Interface interfaceinfo{           function printmessage ();    }        Class ClassA implements interfaceinfo{         function Printmessage () {                 echo "message form Class A";         }    }        Class ClassB implements interfaceinfo{         function Printmessage () {                 echo "message form Class B";         }    }    function Printmsg ($object) {             if ($object instanceof interfaceinfo) {                       $object-printmessage ();             } else{                        echo "Error!";              }    }        $objectA =new ClassA ();    Printmsg ($objectA);     $objectB =new ClassB ();    Printmsg ($objectB);? >

PS. abstract classes and interfaces.

Abstract classes and interfaces are special classes that cannot be instantiated. They are all able to work with object-oriented polymorphism.

Abstract class:

An abstract class is a class that cannot be instantiated and can only be used as a parent class of other classes. Abstract classes are declared with the abstract keyword in the following format:

    

Abstract class Abstraction classes name {Abstract function member method (parameter);//}

Abstract classes are similar to normal classes, including member variables, member methods. The difference is that an abstract class must contain at least one abstract method. Abstract methods have no method body, and the implementation of their functions can only be done in subclasses. Abstract methods are also decorated with keyword abstractions.

Interface:

Inheritance features simplify the creation of objects and classes, and enhance the reusability of code. But PHP only supports single inheritance, and if you want to implement multiple inheritance, use an interface.

Interface declaration: Implemented by the interface keyword, the method declared in an interface must be an abstract method, a variable cannot be declared in an interface, only a member property declared as a constant using the Const keyword, and all members of the interface must have puclic access rights. Ainterface The Declaration interface format is as follows:

  

Inerface Interface Name {         //constant member;//member can only be constant.          //abstract method; }

Because interfaces cannot implement instantiation operations, they can only be implemented in the form of subclass inheritance interfaces. The implemented format is:

Class subclass name implements Interface name 1[, Interface Name 2, interface name 3,.....] {//Sub-class method body.}

Common keywords:

1) The meaning of Final:final is final and final. This is to assume that the classes and methods that are decorated with the final keyword are final. cannot be inherited, nor can there be subclasses. Cannot be overridden or overwritten.

2) Static: member properties and member methods decorated with the static keyword are called static properties and static methods. Static member properties and methods do not need to be instantiated to be used directly.

static property: It belongs to the class itself, not to any instance of the class. It is equivalent to a global variable stored in a class and can be accessed from any location through a class. The Access format is:

Class Name:: $ static property name;

If you want to access a static property in a member method inside the class, precede the name of the static property with the operator: "Self::".

Static methods: Because they are not constrained by any object, static methods in the class can be referenced directly without the instantiation of the class. The reference format is as follows:

Class Name:: Static method name (parameter);

If you want to invoke a static method in a member method inside the class, precede the name of the static method with the operator: "Self::". Only static variables can be called in a static method, not ordinary variables, whereas static variables are called in the normal method.

With static members, in addition to not requiring instantiation, another effect is to retain the modified static data for the next call after the object is destroyed.

3) clone. Cloning of an object can be achieved by keyword. Using the Clone object has no relation to the original object, which means that the cloned object will reapply for a copy of the storage space to hold the original object content. The format is as follows:

$ Clone Object = Clone $ original clone object name;

After cloning succeeds, their n member methods, attributes, and values are exactly equal. _clone () is used if the replica is to be reinitialized.

Magic Method _clone () can reinitialize a cloned copy object. It does not require any parameters, which automatically contain references to $this (Replica objects) and $that (original object) objects.

Comparison of objects:

"= =" means comparing the contents of two objects, and "= = =" means comparing the reference addresses of two objects equal.

Object Type detection: The instanceof operator detects that the current object belongs to that object.

Object-oriented---common magic methods:

The common magic methods we have already learned are: _construct (), _destruct (), _clone. Let's go on to introduce a few common magic methods.

_get (), _set ();

The above two methods are used to fine-copy or get the value of a private member.

_set () sets a value for a private member property in a program run, and it does not require any return value. The _set () method consists of two parameters that cannot be omitted: The variable name and the variable value. This method does not need to be actively called, you can add the Prive keyword in the method money.

_get (): Gets the value of the property of the private member outside the object in the program run. He has a parameter: The private member property name. He returns a value that allows an object to be used externally. This method is also not allowed to be invoked actively.

_isset (), _unset ():

The Isset () function is used to detect whether a variable exists. The Public member property can be instrumented by the isset () function in object-oriented, but this function has no effect on private member properties. Therefore, the _isset () function is created for this purpose. The format is as follows:

BOOL _isset (string name);

_unset () is also intended to remove the private member properties of the variables and objects that are developed. The format is as follows:

void _unset (string name);//

_call ():

The purpose of the _call () method is that when a program attempts to invoke a non-existent or invisible member method, PHP first calls the _call () method to store the method name and its arguments (method name and method arguments). Where the method parameter exists as an array.

_tostring () Method:

The effect is to convert an object to a string when using the Echo or print output object.

If there is no _tostring () method, a fatal error will occur when the object is output directly.

When outputting an object, it should be noted that the Echo or print statement is followed directly by the object to be output, with no extra characters in the middle, or _tosting () will not be executed.

_autoload () Method:

Saving a separate, complete class to a PHP page with a consistent file name and class name is a good habit that every developer needs to develop. This makes it easy to find it the next time you use it. But there is a case: if you want to introduce a lot of classes in a page, you need to use Include_ The once () function or the require_once () function is introduced one by one. The _autoload () method introduced in PHP5 can automatically instantiate the classes that need to be used. When a class is not instantiated, the _autoload () Files with the same class name are automatically found below the specified path. If you find it, continue execution, or you will get an error.

<?php function _autoload ($class _name) {$class _path = $class _name.    Class.php ';    if (file_exists ($class _path)) {include_once ($class _path);    }else{echo ' class does not exist or class path error '; }} $class = new Class ();  will be loaded automatically. Echo $class; Output class content. If the _tostring () method is customized, the content defined in _tostring () is output. >

<?php//接口只能被继承,不能实例化//类可以继承多个接口interfaceinterfaceInfo{    functionprintMessage();};interfaceinterfaceUserinfo{    functionprintUserinfo();};classClassA implementsinterfaceInfo, interfaceUserinfo{    public functionprintUserinfo()    {        echo"ClassA parintUserinfo<BR>";    }    publicfunctionprintMessage()    {        echo"ClassA parintMessage<BR>";    }   };classClassB implementsinterfaceInfo, interfaceUserinfo{    public functionprintUserinfo()    {        echo"ClassB parintUserinfo<BR>";    }    publicfunctionprintMessage()    {        echo"ClassB parintMessage<BR>";    }   };functionprintInterface($obj){    if($objinstanceofinterfaceUserinfo)    {        $obj->printUserinfo();    }else{        echo"error";    }}$classa= newClassA();printInterface($classa);$classb= newclassB();printInterface($classb);

PHP Object-oriented

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.