PHP Object-oriented detailed _php tutorial

Source: Internet
Author: User
Main three attributes of an object
Object behavior: You can apply those actions to objects, turn on the lights, turn off the lights is the behavior.
The shape of the object: When applying those methods is how the object responds, color, size, shape.
Object representation: The representation of an object is equivalent to an identity card, specifically distinguishing between the same behavior and the state of what is different.

Object-oriented model

Object-oriented concepts:
OOP (object-oriented programming) it could be that its code is simpler, easier to maintain and more robust.

What is a class:
A class is a collection of objects that have the same properties and services for example, people, books, ships, cars belong to the class, he made a uniform abstract description of the objects belonging to the class, in the programming language of the class is a separate program, it should have a class name including the description of the property and the service two parts.
What is an object:
An object is an entity that describes an objective event in the system, which 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 manipulate this set of properties.
From an abstract point of view, an object is an abstraction of a problem domain or some thing in the implementation domain. He reflects the information that the thing holds in the system and the role it plays: It is a set of attributes and a wrapper that has permission to manipulate these properties. The objective world is made up of the connections between objects and objects.
Class and object relationships:
The relationship between a class and an object is like the relationship between a mold and a casting, and the result of the strength of the class is the object, and the abstract of the object is the class, which describes a set of objects that have the same attributes (attributes) and the same behavior.

classes and properties and methods

The class syntax format is defined in PHP:
Copy CodeThe code is as follows:
class classname [optional attribute]{
Public $property [=value]; ...//Declare a common identity with a, and then give a variable variable can also assign a value
function functionname (args) {//member functions in Methods of class
Code} ...
Method of the 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 you set or access the variable by an action in the class, use $this->name to refer to it.
Generation of objects
After defining a class with a new to declare, because of the encapsulation characteristics of object data, object can not be accessed directly by the main program block by the object to invoke the properties and behavior functions defined in the class, and indirectly to achieve the purpose of accessing the data in the control class.
Relationship of objects and classes
Relationship of objects and classes:
objects are actually present and occupy dynamic resources.
A class is the blueprint for an object and may occupy a static resource.
Object properties Occupy dynamic resources
A class (static) property is actually a "global variable" on a class namespace
Performance considerations:
Each object consumes data space alone
Increased call hierarchy may consume execution time
Parameter form and delivery mode of the method
The parameters of a method can be basic data types, arrays, and class objects.
Basic data type: Value parameter delivery
Array: Value parameter Pass
Class object: Reference delivery
constructor function
Constructors are functions that initialize in a class
Constructors are generated in the same way as other functions except that their names must be __construct ().
Syntax format:
function __construct (parameter) {
。。。。。。。。
}
Example:
Copy CodeThe code is as follows:
Class person{
Public $name;
Public $sex;
Public $age;
function __construct ($name, $sex, $age) {
echo "I am a constructor
";
$this->name= $name;
$this->sex= $sex;
$this->age= $age;
}

Output Result: Initialization

Destructors

The destructor is automatically executed when the object is detached from its scope (for example, the function where the object is already called). The memory should be freed in the destructor before exiting.
Destructors __destruct destructors do not have any parameters
Example:
Copy CodeThe code is as follows:
Class person{
function _ _destruct ()
{echo "Bye bye!";}
}
$a =new person ();

Type of Access
Public common (public modifier) class inside and outside of the class can be accessed
Private (private modifier) can only be accessed within the class
Protected protected (protected member modifier) subclasses can access classes outside of the class that cannot be accessed

three key features of OOP

Encapsulation, inheritance, polymorphism
Encapsulation: Encapsulation is the combination of the object's properties and behavior into a separate unit.
Encapsulating a class requires two steps 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: hide the implementation details of the class, you can easily add logic control, restrict the unreasonable operation of the attribute, easy to modify the maintainability of the enhanced code.

__get and __set
It is generally said that the private words of the class more in line with the logic of reality.
Two functions are predefined to obtain and apply the value of the operation.
__get gets a value that is usually the value of a field
__set setting value is usually the value of the field
When __call calls a method that does not exist in an object, an error call () is generated to handle the situation.

static properties and methods

The static keyword to declare the Statics method
Static variables that generate a static variable inside a class are capable of being shared by all classes of power. That is, static members are placed in the "Initialize static segment", which is placed when the class is loaded for the first time, allowing each object in the heap to be shared
How to use: self::$ static property, Self:: Static method
static function P () {
echo self:: $country;
echo Self::P i;//Access constant
echo $this->name; only static properties can be manipulated in static methods
Self::p ();
}
External calls: Class:: $ static property, class:: Static method

Const keyword: used to generate constant constants is unique and cannot be changed by a formula constant to 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, which is called B inheritance to Class A.
If a class inherits properties and services from multiple classes, this is called multi-inheritance, usually we become the subclass of the inheriting class as the parent class, only single inheritance in PHP, but a parent class can be inherited by more than one class, but only one parent class, but a subclass can have a child class, but the definition of the class is reduced by inheritance.
Extende declaring an inheritance relationship
Syntax format: Class B Extends A This example indicates that B inherits a
The outer access of the class is valid for the child class
Properties and methods for subclasses and parent classes
The subclass inherits all the contents of the parent class, but the private part of the parent class cannot be accessed directly
The newly added properties and methods in the subclass are extensions to the parent class
A property defined in a subclass with the same name as the parent class is an override of the parent class property, and a method of the same name overrides the parent class method.

Overridden Methods

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

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

Overwrite parent class's original property
Clone object Syntax format $c=clone $p; Object of $c $p output echo $c->name;

Object Comparison
= = = Two comparison operators.
= = Compares the contents of two objects.
= = = is the handle to the comparison object, which is the reference address.

The instanceof operator is used to detect whether an object's strength belongs to a class of type belonging to return true that 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 clone";
}

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

Polymorphism

Polymorphism refers to a property or behavior defined in a parent class that, after the quilt class inherits, can have different data types or behave differently. This makes the same attribute or behavior have different semantics in the parent class and its subclasses.
This means that the same method differs from the result of executing in a subclass with a parent class.
Copy CodeThe code is 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

Abstract methods are used as sub-categories.
Copy CodeThe code is as follows:
Abstract class person{
Public $name;
Abstract function getInfo ();
}

Abstract classes cannot be words of strength, an abstract class must have an abstract method. However, dynamic functions can be defined in abstract classes.
Interface
When a class inherits an interface, it overwrites all methods of the interface, the interface can only declare constants, the method of the interface must be defined as common, otherwise it cannot be inherited, and the interface can inherit from multiple interfaces
Grammar:
Copy CodeThe code is as follows:
Interface pci{
Const type= "PCI";
Public $name; Error
function Start ();
function Stop ();
}

The methods in the interface can be declared as static
Copy CodeThe code is 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 the class:
Copy CodeThe code is as follows:
Permission modifier class Name {//permission Monk symbol: Public,protected,private or omit 3.
Class body; Class is a built-in keyword
}//The class name must follow class, followed by {}. The members of the class are placed between {}.
?>
PS: Before the class keyword can be added to the 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.
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:
Copy CodeThe code is as follows:
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:
Copy CodeThe code is as follows:
function _destruct () {
Method body
};

Object-oriented features: encapsulation, abstraction, polymorphism.
Package:
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:
Copy CodeThe code is as follows:
Class subclass name extends parent class name {
The 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.
Copy CodeThe code is as follows:

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.
Copy CodeThe code is as follows:

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:
Copy CodeThe code is as follows:
Abstract class 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:
Copy CodeThe code is as follows:
Inerface Interface Name {
A constant member;//a member can only be a constant.
abstract methods;
}

Because interfaces cannot implement instantiation operations, they can only be implemented in the form of subclass inheritance interfaces. The implemented format is:
Copy CodeThe code is 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 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.
Copy CodeThe code is as follows:

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

http://www.bkjia.com/PHPjc/326008.html www.bkjia.com true http://www.bkjia.com/PHPjc/326008.html techarticle The behavior of the main three attribute objects of an object: You can apply those actions to an object, turn on the light, turn off the light, or act. The shape of the object: When applying those methods is how the object responds, color ...

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