PHP Object-Oriented notes

Source: Internet
Author: User
Tags autoload define abstract modifiers object serialization string back
===================================================
Object-oriented PHP:

An object is an entity that objectively exists.
A class is a description of an object abstraction.

Concept: The relationship of objects (entities), classes, classes, and objects.

Features of OOP object-oriented Programming: encapsulation, inheritance, polymorphism

Class and object relationships:
The instantiation result of a class is an object (using the New keyword)
An abstract description of an object is a class

===================================================
First, how to define a class, and use

1.1 Syntax Format:
[Modifier] class class name [extends parent class] [implements interface 1[, Interface 2 ...] {
Member properties define variables
"Member methods" define functions
}

1.2 Member Property Format:
Modifier $ variable Name [= default value]; such as: public $name = "Zhangsan";
Note: The member property cannot be a call to an expression with an operator, a variable, a method, or a function. Such as:
Public $var 3 = 1+2;
Public $var 4 = Self::mystaticmethod ();
Public $var 5 = $myVar;
The correct way to define:
Public $var 6 = 100; Normal VALUES (4 scalars: integers, floating-point numbers, booleans, strings)
Public $var 6 = myconstant; Constant
Public $var 7 = self::classconstant; Static properties
Public $var 8 = Array (true, false); Array

Common Property Modifiers: public, protected, private, Static, Var

1.3 Member Method Format:
[modifier] Function Method name (parameter:) {
[Method body]
[Return value]
}

Common method Modifiers: public, protected, private, static, abstract, final

1.4 Object: An instantiation of a class produces an object.
such as: $p = new person ();

1.5 $this Keyword: Represents the object that is currently being used, * which object calls represent which
1. We call our own member property or method in the class using $this.
2. Note: Static methods can not use the $this keyword

===================================================
Two, the construction method and the Destruction method

2.1. Construction Method:
1. When we create an object by using the New keyword, the first method that is automatically executed is called a constructor method.

2. Method name __construct (); Used primarily for initializing objects.
(You can use methods that have the same name as the class names in php4.0 as a construction method)

2.2. Destructor method: The last method that is called automatically when the object is destroyed is called the destructor method.
1.__destruct (); The goal is to release resources (such as closing connections, files, freeing resources)

2. Last automatic call when object is destroyed

===================================================
Three, encapsulation (access control)

3.1 Encapsulation: The "attribute" private or protected, and provides the public setter placement and getter value method

Public (publicly) protected (protected) private (private)
===========================================================
In this class Y Y y
In the Family Y y N
Outside the class Y n n

When a method or property in this class needs to be called outside the public class, use the
No calls are required outside of the protected class, and the family needs to use
Private for security information only for the current class

===================================================
Four, heavy load

4.1 Four Magic methods in property overloading: __set () __get () __isset () __unset ()

__get (): A method that is automatically called when we directly output a non-public property in an object.
And the property name is passed in as the first argument.
__get ($name) {...}//external: $m->priage;

__set (): A method that is automatically called when we directly set a non-public property in an object.
The property name is passed in as the second parameter, with the first parameter as the value.
__set ($name, $value) {...}//external: $m->priage = 100;

__isset (): When validating an object property isset ($this->name) or empty ($this->name), this method is called automatically when $this->name is a non-public property.
Public Function __isset ($param) {
Return Isset ($this-$param);
}

__unset () This method is automatically called when an object property unset ($this->name) is destroyed, $this->name is a non-public property.
Public Function __unset ($param) {
Unset ($this, $param);
}

Overloads of the 4.2 method:
Mixed __call (string $name, array $arguments)
Mixed __callstatic (string $name, array $arguments) php5.3.0 support

1. __call () is called when an inaccessible method, such as undefined or invisible, is invoked.
2. __callstatic () is called when a non-accessible method is called in a static method, such as undefined or invisible.

The first parameter represents the method name, and the second parameter represents the list of arguments at the time of invocation (array type)

Class A {
Calling a method that does not exist
Public Function __call ($methodName, $args) {
Echo $methodName;
Print_r ($args);
}

Calling a static method that does not exist
static public Function __callstatic ($methodName, $args) {
Echo '
'. $methodName;
Print_r ($args);
}
}
$a = new A;
$a->say (' A ', ' B ');
A::test (' C ', ' d ');

===================================================
V. Inheritance

5.1 Inheritance: Extends
* The purpose of inheritance: In order to reduce duplicate code.

If Class B inherits Class A, then all non-private properties and methods in a are inherited. Where A is called a parent class (base class) B is called a subclass (derived class).
Class B extends a{
....
}

1.*parent: If a subclass has a method that overrides the parent class, it wants to call the overridden parent method and can fuse it with the method of the subclass

Format: Parent:: Parental method | Parent class Name:: Parent class method

Class a{
Public Function __construct () {
//....
}
}
Class B extends a{
Public Function __construct () {
Parent::__construct ();//Note to invoke the constructor method of the parent class
//....
}
}

2. Characteristics of inheritance
1, PHP support single inheritance, a class can inherit only one parent class
2, PHP support multilayer inheritance, can have descendants of the class
3. Subclasses inherit all the properties and methods of the parent class, but private properties and methods cannot be called

3. Inheritance of attributes
1, private properties will not be overwritten, others will be overwritten.
2, the property decoration can only be more loose, not more rigorous. Loose: public > Protected > Private
3. If a subclass has a property with the same name as the parent class, the parent class has public $name child classes can only be decorated with public
3. If a subclass has a property with the same name as the parent class, the parent class has protected $name subclasses can use the protected,public adornment

4. Inheritance of methods
1. All methods can be inherited, but private methods cannot be used
2. If a subclass has a method with the same name as the parent class, all but the private method is overwritten.
3. If a subclass has a method with the same name as the parent class, the method's adornment can be more loose and not more rigorous.

===================================================
Vi. final, Static and const
* Memory Logic: Constant area (constant, static property), code area (class, function), stack memory (normal small variable), heap memory (large variable)

6.1 Final keyword: primarily used to decorate classes and Member methods
Purpose: One is for security, two is not necessary

1. Use the final keyword to modify the class to indicate that the class cannot be inherited, and that there are no overrides for subclasses

2. Methods that are decorated with the final keyword cannot be overridden in subclasses (Overrides).

3. Use the final keyword to not decorate a property

Final class B {
Final Public Function A {
..
}
}
---------------------------------------------------------------
6.2 Static Keyword: represents static meaning, which is used to modify the properties and methods of a class

The Static keyword-decorated property/method is called a Statics property/static method,
Note: Static methods do not have access to the static method name,//$ object name, after the instantiation of the object

1. You can use methods or properties directly without new (instantiation)
* External call: Class Name:: Method name | Class Name:: Property name
* Called in class: Self:: static property name | Self:: Static method Name

The static properties are shared. That is, calling multiple objects also points to the same address

3. Non-static content cannot be used in static methods. is not to use $this

4. In a method of a class, if no $this call appears, the default method is static.

5.static cannot modify class

---------------------------------------------------------------
6.21 design mode. Purpose: Save resources

1. Single case design mode 2, factory design mode 3, abstract factory design mode

Class single
{
Define a static property to hold the object
static private $obj = NULL;

Privatization of construction methods. Cannot instantiate an object outside of a class
Private Function __construct () {}

Instantiating an Object
static public Function test () {
If there is no object, we allow it to be a new object
if (!self:: $obj) {
Self:: $obj = new single ();//Create Object
}

When you have an object, you return directly to the previous object
Return self:: $obj;
}

Single case does not allow cloning
Public Function __clone () {
Trigger_error (' Error ', e_user_error);
}
}

$s 1 = single::test (); Var_dump ($s 1);
$s 2 = single::test (); Var_dump ($s 2); Call the same object

$s 3 = clone $s 2; Error

---------------------------------------------------------------
6.3. CONST keyword: Modifies a member property in a class, defines it as a constant (non-modifiable),

1. General requirements The constant name is uppercase, there is no "$" character no other modifier (public)

2. Definition Format: Const member Constant NAME = "value";

3. Use:
* External call: Class Name:: member constant name;
* Called in class: Self:: member constant name;

---------------------------------------------------------------
6.4. Detect which class the current object belongs to (family class is also)

1.instanceof is used to determine if a PHP variable belongs to an instance of a class class:

Class A {}
Class B extends A {}
$b = new B;
if ($b instanceof A) {echo ' Y ';}

2.is_a-returns TRUE if the object belongs to the class or if the class is the parent class of this object

===================================================
VII. type constraints

1. Types that can be used by type constraints are: arrays, objects, callback functions.
If you specify a class name, you can pass in the object of this class and subclass.
Types of constraints that can be used: Array, class name, abstract class name, interface name (compound type)

Class MyClass
{
The first argument must be an object of class Otherclass
Public function test (Otherclass $otherclass) {
* * You can pass in other classes, calling methods and properties of other classes
Echo $otherclass->var;

with here
if ($otherclass instanceof Hanzi) {
$otherclass->qinqin ();
}
}

The first parameter must be an array
Public function Test_array (array $input _array) {
Print_r ($input _array);
}
}

===================================================
Eight, other magic methods:

1. Object replication clone clones an object because the object belongs to a reference type, and the normal "=" number belongs to the reference assignment,
All you need is clone to duplicate a copy.
Magic method: __clone () method that is automatically called when a clone clone is executed.

Class A {
Public Function __clone () {
Automatic execution
}
}

$a = new A;
$b = Clone $a; Clone, is two objects

-----------------------------------------------------------------
2. __tostring () Method: Magic method, when we want to output an object directly, such as Echo $a, print $a,
Then the method is automatically called.
Note: the __tostring () method must return a string of type value.

Class A {
Public Function __tostring () {
Return ' This is an object that does not allow ehco,print ... ';
}
}
$a = new A;
echo $a; Error

-----------------------------------------------------------------
3. * Auto Load "class function" __autoload (class name):
When new instantiates an object, the class does not exist, the function is called automatically, and the class name is stored in the parameter
I can use this implementation to automatically load the class.

function __autoload ($className) {
Include './autoload/'. $className. Class.php ';
}

$a = new A;
$a->say (); Say

Under the autoload/a.class.php
Class a{
Public function say () {
Echo ' say ';
}
}

-----------------------------------------------------------------
4. __invoke automatically calls objects when they are used as functions

Class A {
Public Function __invoke () {
echo ' AA ';
}
}

$a = new A;
$a (); Aa

===================================================
Nine, object serialization (serialization) (WebService XML) (used in object persistence storage, and transport)

Serialize ()--serialization
Unserialize ()--de-serialization

The values inside the 1.php can be represented by using the function serialize () to return a string containing a stream of bytes.
The 2.unserialize () function can re-change the string back to the original PHP value.
3. Serializing an object saves all variables of the object, but does not save the object's methods, only the name of the class is saved.

1.__sleep (): is a method that is automatically invoked when serialization is performed to implement the close operation of a property of a resource type.
The @ @sleep method needs to return an array where the values in the array are the property names to preserve when serializing
2.__wakeup (): is a method that is called automatically when performing a crossdress, to enable the opening of a resource property (a resource closed by the Sleep method)

Instance:
Class A {
Public $name 1 = ' Xiaohei ';
Public $name 2 = ' Xiaobai ';

Public Function demo () {
return ' AA ';
}

Methods for serializing automatic calls
Public Function __sleep () {
Return Array (' name2 '); Just want to store name2, return to Name2
}

Methods for deserializing automatic calls
Public Function __wakeup () {
Echo ' # # # ';
}
}

$a = new A;

Serialization of
$data = serialize ($a);

Deposit file
File_put_contents ('./1.txt ', $data);

Get the data
$str = file_get_contents ('./1.txt ');

Echo $str; O:1: "A": 1:{s:4: "Name"; s:7: "Xiaohei";}

Deserialization
$tmp = Unserialize ($STR);

Print_r ($TMP); A Object ([name] = = Xiaohei)

-------------------------------------------------------------------------------------
Encode/decode a string in JSON format

Json_encode: JSON Encoding of variables
Json_decode: Encoding a JSON-formatted string

$arr = array (' ID ' =>1, ' name ' = ' Jack ');

$str 1 = json_encode ($arr);
echo $str 1; {"id": 1, "name": "Jack"}

$a = Json_decode ($str 1, true); Adds true to return an array, otherwise returns an object
echo $a; Array ([id] = 1 [name] = + Jack)

===================================================
X. Abstract class:

Objective: Abstract classes have a binding effect on subclasses (Implementation classes),

Characteristics:
1. Defining abstract Classes
Abstract class A {
2. Defining abstract methods
Abstract public Function test1 ();
Abstract public Function test2 ();

3. Can have common methods and properties, do not need children to implement
Public Function Demo () {}
Public $name = ' AA ';

4. Cannot define abstract attribute Fatal error
Abstract public $age = 18;
}

Class B extends A {
5.@@ inherits the "ordinary class" of an abstract class that must implement "all abstract methods" of the abstract class
Public Function Test1 () {}
Public Function Test2 () {}

6. The class containing the abstract method must be an abstract class, Fatal error
Abstract function Test3 () {}
}

Abstract class C extends A {
7. Cannot overwrite abstract method, Fatal error
Abstract public Function Test1 () {}

8. You can inherit abstract classes and add abstract methods at the same time
Abstract public Function test3 ();
}

8. Cannot instantiate, Fatal error
$c = new C;

===================================================
Xi. Interface:

Purpose: Same as abstract class, is more specific abstract class
If all the methods in an abstract class are abstract, then we can define it in another way: interface
The interface is defined using the keyword interface, which can only have constants and abstract methods.

1. Defining the interface
Interface A {
2. Interface cannot have normal properties, Fatal error
Public $name = ' AA ';

3. Interface cannot have normal method, Fatal error
Public Function Test () {}

3. But you can define constants
Const HOST = ' AA ';

4. Define interface methods, no abstract required
Public function test1 ();

}

Interface B {
5. Interface is an inheritance relationship, duplicate definition fatal error
Const HOST = ' BB ';

Public function test2 ();
}

Class C {}

6. Can inherit "single" class, implement "Multi" interface (inherit first, implement later)
Class D extends C implements A, B {
7.@@ inherits the "ordinary class" of an abstract class that must implement "all abstract methods" of the abstract class
Public Function Test1 () {}
Public Function Test2 () {}
}

Abstract classes and Interfaces summary:
1. Purpose: To establish a norm in order to limit its sub-categories
2. Select: If you need a "normal method" in the specification, select the abstract class
3. Difference:
1. Define keywords differently. Abstract class: Abstraction Interface: interface
2. Inheritance/implementation keywords are different. Abstract class: Extends interface: Implements
3. Abstract classes can have common methods, interfaces can not have a common method
4. Abstract classes can only be inherited, interfaces can be implemented more
5. Interfaces cannot have member properties, only constants and abstract methods

===================================================
12. polymorphic

Definition: For "The same method", passed "different objects", achieve different effects

Class Meizi {
Public function Meet ($obj) {
Limit the object must have Qinqin () this method
if ($obj instanceof Hanzi) {
The same method
$obj->qinqin ();
}else{
Echo ' You won't kiss this feature! ';
}
}
}

Abstract class
Abstract class Hanzi
{
Abstract public Function qinqin ();
}

Big cock Silk class
Class DDS extends Hanzi {
Public Function Qinqin () {
Echo ' was slapped by sister, this is the fate of DDS ';
}
}

Ko Fu Handsome class
Class GFS extends Hanzi {
Public Function Qinqin () {
Echo ' Not only kisses, but also POPs, this is the fate of Gaofu ';
}
}

Cute Sister class
Class Mengmeizi {}

$m = new Meizi;
$dds = new DDS;
$gfs = new GFs;
$mmz = new Mengmeizi;

Incoming Object
echo $m->meet ($DDS); Realize the effect of DDS
echo $m->meet ($GFS); Realize the effect of GFs

No Limits
echo $m->meet ($MMZ); You don't kiss!

Two examples of @@ polymorphism:
/1. Multi-state applications via interfaces. php
./2. The application of polymorphism is realized by common class. php

===================================================
13. Exception Handling:
There is a new error handling mechanism in PHP5-exception handling: (using object-oriented approach)
Classes involved: Exception Exception class
Exception class Structure:
Class Exception
{
protected $message = ' Unknown exception '; Exception information
protected $code = 0; User-defined exception codes
protected $file; The file name of the exception that occurred
protected $line; The line number of the code where the exception occurred

function __construct ($message = null, $code = 0);

Final function getMessage (); Return exception information
Final function GetCode (); Return exception code
Final function getFile (); Returns the file name of the exception that occurred
Final function getLine (); Returns the line number of the code where the exception occurred
Final function gettrace (); BackTrace () array
Final function gettraceasstring (); Gettrace () information that has been rasterized into a string

/* Overloaded method */
function __tostring (); A string that can be output
}

Use:
try{
throw new Exception ("Age cannot be negative"); Exception throws
}catch (Exception $e) {
Exception handling
echo $e->getmessage ();
}

Instance:
function AddUser ($username) {
if ($username = "Xiaobai") {
Add success
}else {
Add failed
throw new Exception (' Add failed ');
}
}

function UpdateUser ($username) {
if ($username = "Xiaohei") {
Modification succeeded
}else {
Modification failed
throw new Exception (' Modify failed ');
}
}

try {
AddUser (' Xiaobaia ');

UpdateUser (' Xiaohei ');
}catch (Exception $e) {

Echo ' Failure message is: '. $e->getmessage ();
}

@@ After an exception is caught, subsequent code inside the try () block does not continue to execute

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