PHP Object-oriented detailed _php skills

Source: Internet
Author: User
Tags constant modifier modifiers
The main three attributes of an object
Object behavior: You can apply those actions to the object, turn on the light, turn off the light is behavior.
The shape of the object: When applied to those methods is how the object responds, color, size, and shape.
Object representation: The representation of an object is equivalent to an identity card, which distinguishes between the same behavior and the state.

Object-oriented model

Object-oriented concepts:
OOP (object-oriented programming) it makes its code simpler and easier to maintain and more resilient

What is a class:
A class is a collection of objects with the same attributes and services, such as people, books, ships, cars all belong to the class, he made a unified abstract description of objects belonging to the class, in programming language class is a separate program, it should have a class name including attribute description and service two parts.
What is an object:
An object is an entity that describes an objective event in a system, and he is a basic unit of the system. * Data and code are bundled in an entity *, an object consists of a set of properties and a set of behaviors that operate on the set of attributes.
From an abstract point of view, an object is an abstraction of something in the problem domain or implementation domain. He reflects the information and role that the thing holds in the system: it is a set of properties and a package that has permission to operate on these properties. The objective world is made up of the relationship between objects and objects.
Relationships between classes and objects:
The relationship between the class and the object is like the relationship between the mold and the casting, the result of the strength of the class is the object, and the abstraction of the object is the class, and the class describes the set of objects with the same attributes (attributes) and the same behavior.

classes and properties and methods

Define class syntax format in PHP:
Copy Code code as follows:

class classname [optional attribute]{
Public $property [=value];///To declare a common identity and give a variable variable can also be assigned a value
member functions in Methods of function functionname (args) {//Class
Code} ...
Method of a class (member function)
}

Build object (Instantiation of Class): $ object Name =new classname ();

using the properties of an object

In a class, you can access a special pointer $this when the variable is set or accessed through an action in the class, referenced using $this->name.
Generation of objects
After the definition of a class with a new to declare that, because of the encapsulation characteristics of object data, objects can not be directly accessed by the main program block through the object to invoke the defined attributes and behavioral functions, indirectly to achieve access control class data.
The relationship between objects and classes
The relationship between objects and classes:
Objects are real and occupy dynamic resources.
A class is the blueprint of an object and may occupy static resources.
Object properties Occupy dynamic resources
A class (static) property is actually a "global variable" on a class namespace
Performance considerations:
Each object takes up data space alone
Increased call levels may consume execution time
Parameter form and transfer mode of the method
The parameters of a method can be basic data types, arrays, and class objects.
Basic data type: Value parameter Pass
Arrays: Value parameter passes
Class objects: Reference passing
Constructors
constructors function as initialization in a class
Constructors are generated in the same way as other functions except that their name must be __construct ().
Syntax format:
function __construct (parameters) {
。。。。。。。。
}
Example:
Copy Code code as follows:

Class person{
Public $name;
Public $sex;
Public $age;
function __construct ($name, $sex, $age) {
echo "I am a constructor <br>";
$this->name= $name;
$this->sex= $sex;
$this->age= $age;
}

Output Result: Initialization

destructor

The system performs the destructor automatically when the object is detached from its scope (for example, the function where the object is already called). You should use freed memory in the destructor before exiting.
Destructors __destruct destructors do not have any arguments
Example:
Copy Code code as follows:

Class person{
function _ _destruct ()
{echo "Bye bye!";}
}
$a =new person ();

Access type
Public common (public modifier) classes are accessible both inside and outside of the class
Private private modifiers can only be accessed within a class
Protected protected (protected member modifier) subclasses can access the outside class

three important features of OOP

Encapsulation, inheritance, polymorphism
Encapsulation: Encapsulation is the combination of the object's attributes and behavior into a separate unit.
It takes two steps to encapsulate a class. The first step is to privatize a class the second step is to use set and get to make read assignment operations
His advantage is: hidden class implementation Details, you can easily add logic control, restricting the property of unreasonable operation, easy to modify the maintenance of enhanced code.

__get and __set
Generally speaking, the class of private words more in line with the logic of reality.
There are two predefined functions for obtaining and applying operations.
__get gets a value that is usually the value of a field
__set set value is usually the value of a field
When __call calls a method that does not exist in an object, it generates an error called () method to handle the situation.

static properties and methods

Static keyword to declare a stationary method
Static static variables within the class to generate a statically variable is to be able to be all classes of the strength of the total thought that static members are placed in the "initialization static segment", in the first time the class was loaded, you can let the heap memory of each object to share
How to: self::$ static properties, Self:: static methods
static function P () {
echo self:: $country;
echo Self::P i;//Access Constants
Echo $this->name; can only manipulate static properties in a static method
Self::p ();
}
External calls: Class:: $ static properties, classes:: Static methods

Const keyword: used to generate constant constants is the only immutable formula constant is uppercase
Const CONSTANT = ' CONSTANT value '; Generate a constant
echo self::constant;//class internal access
echo classname::constant;//class external access

Inheritance of

The objects of Class B have all the properties and behaviors of Class A, called B Inheritance of Class A.
If a class inherits attributes and services from multiple classes, this is called multiple inheritance, usually we become inheriting classes for subclasses are inherited classes are parent classes, in PHP only single inheritance, but a parent class can be inherited by more than one class, but a subclass can have only one parent class, but allow association inheritance, through inheritance can reduce the definition of the class.
Extende Declaration Inheritance Relationship
Syntax format: Class B Extends A This example indicates that B inherits a
External access to the class is valid for the subclass
Properties and methods of subclasses and parent classes
The subclass inherits all the contents of the parent class, but the private part of the parent class cannot directly access the
The newly added properties and methods in subclasses are extensions to the parent class
A property defined in a subclass that has the same name as the parent class is an overlay of the parent class property, and a method with the same name overrides the parent class method

methods of rewriting

In subclasses, use parent to access overridden properties and methods in the parent class

Parent::__construce ();
Parent:: $name;
Parent::fun ();

Overwrite parent Class original attribute
Clone Gram Object Syntax format $c=clone $p; $c the object $p output echo $c->name;

Object Comparison
= = = Two comparison operators.
= = is the content of the comparison two objects.
= = = is the handle of the comparison object, that is, the reference address.

The instanceof operator is used to detect whether an object's strength belongs to a class of a type belonging to return true does not belong to return false
__clone () If you want to change the contents of the original object after cloning, you need to rewrite the original properties and Methods in __clone ()
function __clone () {
$this->name= "I am a human cloning";
}

Final indicates that a class is a final version, which means that it cannot be invoked in the quilt class

Polymorphism

Polymorphism refers to the attributes or behaviors defined in the parent class that inherit from the quilt class and can have different data types or behave differently. This makes the same property or behavior have different semantics in the parent class and its subclasses.
This means that the same method performs differently in subclasses than in the parent class.
Copy Code code as follows:

Class A {
function info () {
echo "A INFO";
}
}
Class B extends A {
function info () {
echo "B INFO";
}
}
Class C extends A {
function info () {
echo "C INFO";
}
}
function Printinfo ($obj) {
function Printinfo (A $obj) {
if ($obj instanceof A)
$obj->info ();
$obj->info ();
}
}
$a =new A (); $b =new B (); $c =new C ();
Printinfo ($a); Output a INFO
Printinfo ($b); Output b INFO
Printinfo ($c); Output C INFO


abstract methods and abstract classes

The abstract method is used as a subclass of the touch version.
Copy Code code as follows:

Abstract class person{
Public $name;
Abstract function getInfo ();
}

An abstract class cannot be a powerful word, and an abstract class must have an abstract method. However, you can define dynamic functions in an abstract class.
Interface
When a class inherits an interface, it overwrites all the methods of the interface, the interface can only declare constants, and the interface's methods must be defined as common or cannot be inherited, and interfaces can inherit between multiple interfaces
Grammar:
Copy Code code as follows:

Interface pci{
Const type= "PCI";
Public $name; Error
function Start ();
function Stop ();
}

The method in the interface can be declared as static
Copy Code code as follows:

Interface a{function A ();}
Interface b{function B ();}
Interface C extends a{function C ();}
Class D implements b,c{
function A () {}
Function B () {}
Function C () {}
}

class
Declaration of a class:
Copy Code code as follows:

<?php
Permission modifiers class class name {//permission Monk symbol: Public,protected,private or omit 3.
Class body; Class is the Build keyword
//The class name must follow the class, followed by {}. The members of the class are placed between {}.
?>
PS: In the class keyword before you can add permission modifiers, you can add static,abstract and other keywords. A class, that is, the entire contents of a pair of curly braces in a section of code, does not allow the contents of a class to be split into pairs blocks.
<?php
Class conndb{
//....
?>
?
//...
};
?>

member Properties:
A variable declared directly in a class is called a member property/variable. Its type can be a scalar type and a composite type 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 it: a keyword that has a specific meaning: public,protected,private; no need for a particular meaning: var. When declaring a member property, it is not necessary to assign an initial value.

member constants:

Decorated with a const constant, for example: const PI = 3.1415926;
The output of a constant is not instantiated and can be invoked directly by 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, it is a special object to use the method. The member method belongs to that object, $this application represents that object, and its function is to specifically complete the access between the members within the object.
2 "::" becomes the scope operator, using this operator to invoke constants, variables, and methods in a class without creating an object. The syntax format is as follows:

Keywords:: variable name/constant name/method name

Keyword: parent, you can invoke member variables, member methods, and constants in the parents class members;
Self, you can call static members and constants in the current class;
Class name, you can call constants, variables, and methods in a class;
  
member Methods:

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

  To create an object:

$ Variable name = new class name ([parameters]); The instantiation of the class.
To access a class member:
$ variable Name-> member property = value;
Construction method and destructor method
A constructor is a method that is invoked automatically by the first object after the creation of an object. It exists in the declaration of each class, is a special member method, and is generally used to complete some initialization. If there is no construction method in the class, the system automatically generates a construction method without parameters by default.
Format:
Copy Code code as follows:

function _construct (parameter list) {
Method body
};

A destructor, as opposed to a constructed method, is the last method called before an object is destroyed. It will complete a specific operation, such as closing the file and freeing the memory.
Format:
Copy Code code as follows:

function _destruct () {
Method body
};

Object-oriented features: encapsulation, abstraction, polymorphism.
Encapsulation:
Combine the member properties and methods in a class into a separate, identical unit, and hide the details of the object as much as possible. The purpose is to ensure that parts other than classes are not arbitrarily accessible to the internal data of the class (member properties and member methods), thus avoiding the impact of external errors on internal data.
The encapsulation of the class is implemented through the keyword public,private,protected,static and final. The function of each keyword please check the PHP related documentation.
Inheritance:
Makes a class inherit and owns the member properties and member methods 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 your code. The inheritance of the class is used extends keyword.
Format:
Copy Code code as follows:

Class subclass name extends parent class name {
The subclass method body.
}

Parent:: Keyword You can also call the member method of the superclass in a subclass method, as follows:
Parent:: The member method (parameter) of the parental class;

methods that override the parent class:

The so-called method of overriding the parent class is to replace the method inherited from the parent class with the method in the subclass, also called the 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. PHP polymorphism has two implementations, that is, to implement polymorphism through inheritance and polymorphism through interfaces.
Polymorphism is achieved through inheritance, that is, by overriding inherited member methods to achieve polymorphic effects.
Copy Code code as follows:


<?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 the interface, and the null method. Then the class inherits the interface.
Copy Code code as follows:


<?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 of other classes. Abstract classes are declared with the abstract keyword, in the following format:
Copy Code code as follows:

Abstract class Name {
Abstract function member method (parameter);//
}

Abstract classes are similar to ordinary classes, including member variables, member methods. The difference is that an abstract class must contain at least one abstract method. Abstract methods do not have a method body and the implementation of its functionality can only be done in subclasses. Abstract methods are also decorated with the keyword abstract.

Interface:
Inheritance features simplify the creation of objects and classes, and enhance the reusability of your code. But PHP only supports single inheritance, and if you want to implement multiple inheritance, use an interface.
Declaration of an interface: implemented by the interface keyword, the method declared in the interface must be an abstract method, a variable cannot be declared in an interface, only a member property declared as a constant by using the Const keyword, and all members of the interface must have puclic access. Ainterface The Declaration interface format is as follows:
Copy Code code as follows:

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

Because an interface cannot be instantiated, it can only be implemented in the form of a subclass inheritance interface. The format of the implementation is:
Copy Code code as follows:

Class subclass name implements Interface name 1[, Interface Name 2, interface name 3,.....] {
The subclass method body.
}

Common keywords:
1) The meaning of Final:final is final and final. This means that the classes and methods that are decorated with the final keyword are final. cannot be inherited or have 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 the equivalent of a global variable stored in a class that can be accessed at 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 within a class, precede the name of the static property with the operator: "Self::".
Static methods: Because they are not subject to any object restrictions, static methods in a class can be referenced directly without instantiating the class. The reference format is as follows:
Class Name:: Static method name (parameter);
If you want to call a static method in a member method within a class, precede the name of the static method with the operator: "Self::". Static variables can only be invoked in static methods, not ordinary variables, and static variables can be invoked in normal methods.
Using static members in addition to not requiring instantiation, another effect is that after the object is destroyed, still retain the static data modified so that the next call.
3 clone. The cloning of an object can be achieved by using a keyword. The Clone object has nothing to do with the original object, which means that the cloned object will reapply for a storage space to hold the original object content. The format is as follows:
$ Clone Object = Clone $ original clone object name;
After the clone succeeds, their N member methods, properties, and values are exactly equal. _clone () is used if you want to reinitialize the replica.
Magic Method _clone () can reinitialize a cloned replica object. It does not require any arguments, which automatically contain references to $this (Replica objects) and $that (original object) objects.
Comparison of objects:
"= =" represents the contents of a comparison of two objects, and "= =" indicates that the reference address of two objects is equal.
Detection of object types: The instanceof operator can detect 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 some common magic methods.
_get (), _set ();
The above two methods are used for fine copying or fetching values for private members.
_set () Sets the value for the private member property in the program's run, and it does not need any return value. The _set () method includes two parameters that cannot be omitted: variable name and variable value. This method does not require unsolicited calls, which can be added in the method money with the Prive keyword.
_get (): Gets the value of the property of a private member outside the object in the program run. He has one argument: Private member property name. He returns a value that allows the object to be used externally. This method is also not allowed to be invoked voluntarily.

_isset (), _unset ():
The Isset () function is used to detect whether a variable exists. While in object-oriented objects, the public member properties can be detected by the Isset () function, but this function does not work for private member properties. Therefore, the _isset () function is created for this purpose. The format is as follows:
BOOL _isset (string name);
_unset () is also to delete the established variables and the private member properties of the object. The format is as follows:
void _unset (string name);//
_call ():
The effect of the _call () method is that when a program attempts to invoke a member method that does not exist or is not visible, PHP first calls the _call () method to store the method name and its arguments (method name and method parameters). Where the method arguments are in the form of an array.
_tostring () Method:
The effect is to convert an object to a string when you use Echo or print to output an object.
If there is no _tostring () method, a fatal error occurs when the object is output directly.
When you output an object, you should note that the Echo or print statement is followed directly by the object to be output, without extra characters in the middle, otherwise _tosting () will not be executed.
_autoload () Method:
Save a separate, complete class to a PHP page, and the file name is consistent with the class name, which is a good habit that every developer needs to develop. The next time you use it, you can easily find it. But there is a situation: if you want to introduce a lot of classes in a page, you need to use the Include_ The once () function or the require_once () function is introduced into the. PHP5 introduces the _autoload () method to automatically instantiate the class that needs to be used. When a class is not instantiated, _autoload () Automatically finds files with the same class name automatically below the specified path. If found, continue with the error.
Copy Code code as follows:


<?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.
?>

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.