New Features of PHP5: more object-oriented PHP

Source: Internet
Author: User
Tags autoload rewind

PHP has completely re-developed the kernel for processing objects, providing more functions while improving performance. In earlier versions of php, the methods for processing objects and basic types (numbers, strings) are the same. This method has the following drawbacks: when an object is assigned to a variable or an object is passed through a parameter, the object will be completely copied. In the new version, the above operations will pass references (which can be understood as object identifiers), rather than values.

Many PHP programmers may not even notice the old object processing method. In fact, most php applications can run well. Or few changes are required.

Private and protected members
PHP5 introduces the concept of private and protected member variables. We can use it to define the visibility of class members.

Example
Protected members can be accessed by the quilt class, while private members can only be accessed by the class itself.

<? Php
Class MyClass {
Private $ Hello = "Hello, World! \ N ";
Protected $ Bar = "Hello, Foo! \ N ";
Protected $ Foo = "Hello, Bar! \ N ";

Function printHello (){
Print "MyClass: printHello ()". $ this-> Hello;
Print "MyClass: printHello ()". $ this-> Bar;
Print "MyClass: printHello ()". $ this-> Foo;
}
}

Class MyClass2 extends MyClass {
Protected $ Foo;

Function printHello (){
MyClass: printHello ();/* shocould print */
Print "MyClass2: printHello ()". $ this-> Hello;/* Shouldn't print out anything */
Print "MyClass2: printHello ()". $ this-> Bar;/* Shouldn't print (not declared )*/
Print "MyClass2: printHello ()". $ this-> Foo;/* shocould print */
}
}

$ Obj = new MyClass ();
Print $ obj-> Hello;/* Shouldn't print out anything */
Print $ obj-> Bar;/* Shouldn't print out anything */
Print $ obj-> Foo;/* Shouldn't print out anything */
$ Obj-> printHello ();/* shocould print */

$ Obj = new MyClass2 ();
Print $ obj-> Hello;/* Shouldn't print out anything */
Print $ obj-> Bar;/* Shouldn't print out anything */
Print $ obj-> Foo;/* Shouldn't print out anything */
$ Obj-> printHello ();
?>

Private and protected Methods
PHP5 also introduces the concepts of private and protected methods.

Example:
<? Php
Class Foo {
Private function extends vatemethod (){
Echo "Foo: aPrivateMethod () called. \ n ";
}

Protected function aProtectedMethod (){
Echo "Foo: aProtectedMethod () called. \ n ";
$ This-> aPrivateMethod ();
}
}

Class Bar extends Foo {
Public function aPublicMethod (){
Echo "Bar: aPublicMethod () called. \ n ";
$ This-> aProtectedMethod ();
}
}

$ O = new Bar;
$ O-> aPublicMethod ();
?>

The previous code that does not use the class and does not have an access modifier (public, protected, private) can be run without modification.

Abstract classes and abstract methods
Php5 also introduces the concept of abstract classes and abstract methods. Abstract METHODS only declare the method signature and do not provide its implementation. Classes that contain abstract methods must be declared as abstract classes.

Example:
<? Php
Abstract class AbstractClass {
Abstract public function test ();
}

Class ImplementedClass extends AbstractClass {
Public function test (){
Echo "ImplementedClass: test () called. \ n ";
}
}

$ O = new ImplementedClass;
$ O-> test ();
?>

Abstract classes cannot be instantiated. The old code that does not use abstract classes can be run without modification.

Interface
Php5 introduces the interface. A class can implement multiple interfaces.

Example:
<? Php
Interface Throwable {
Public function getMessage ();
}

Class MyException implements Throwable {
Public function getMessage (){
//...
}
}
?>

The old code that does not use interfaces can be run without modification.

Class type prompt

PHP5 is still of weak type. However, when defining function parameters, you can use the class type prompt to declare the expected object type.

Example
<? Php
Interface Foo {
Function a (Foo $ foo );
}

Interface Bar {
Function B (Bar $ bar );
}

Class FooBar implements Foo, Bar {
Function a (Foo $ foo ){
//...
}

Function B (Bar $ bar ){
//...
}
}

$ A = new FooBar;
$ B = new FooBar;

$ A-> a ($ B );
$ A-> B ($ B );
?>

Like other strong-type languages, type prompts of the php5 class are checked during runtime rather than during compilation. That is:

<? Php
Function foo (ClassName $ object ){
//...
}
?>

It is the same as the following code:

<? Php
Function foo ($ object ){
If (! ($ Object instanceof ClassName )){
Die ("Argument 1 must be an instance of ClassName ");
}
}
?>

This syntax only applies to classes and does not apply to built-in types.

Final

PHP 5 introduces the final keyword to declare the final member and final method. The final member and final method cannot be overwritten by the quilt class.

Example
<? Php
Class Foo {
Final function bar (){
//...
}
}
?>

Further, the class can be declared as final. Declaring a class as final can prevent the class from being inherited. The methods in the final class are all final by default and do not need to be declared again.

Example
<? Php
Final class Foo {
// Class definition
}

// The next line is impossible
// Class Bork extends Foo {}
?>

The attribute cannot be defined as final.

The old code without using final can be run without modification.

Object cloning
Php4 does not provide a mechanism for users to define their own copy constructor to control the copying process of objects. Php4 performs binary copying, so it precisely copies all attributes of an object.

Accurately copying all attributes of an object may not be what we always wanted. An example shows that we really need to copy the constructor, for example, a GTK Window object. A holds all the resources it needs. When copying the GTK Window to object B, we want B to hold a new resource object. Another example: Object a contains Object c. When you copy object a to object c. We may want object B to include a new object c copy instead of a reference to object c. (Note: what we talk about here is shortest cloning and deep cloning .)

Object replication is achieved through the clone keyword (Clone calls the _ clone () method of the cloned object ). The _ clone method of an object cannot be called directly.

<? Php
$ Copy_of_object = clone $ object;
?>

When the developer creates a copy of an object, php5 checks whether the _ clone () method exists. If it does not exist, it will call the default _ clone () method to copy all attributes of the object. If the _ clone () method has been defined, the _ clone () method is responsible for setting the attributes of the new object. For convenience, the Engine copies all attributes by default. Therefore, in the _ clone () method, you only need to overwrite the attributes that need to be changed. As follows:
Example
<? Php
Class MyCloneable {
Static $ id = 0;

Function MyCloneable (){
$ This-> id = self: $ id ++;
}

Function _ clone (){
$ This-> address = "New York ";
$ This-> id = self: $ id ++;
}
}

$ Obj = new MyCloneable ();

$ Obj-> name = "Hello ";
$ Obj-> address = "Tel-Aviv ";

Print $ obj-> id. "\ n ";

$ Obj_cloned = clone $ obj;

Print $ obj_cloned-> id. "\ n ";
Print $ obj_cloned-> name. "\ n ";
Print $ obj_cloned-> address. "\ n ";
?>

Unified Constructor
Php5 allows developers to declare the constructor of a class. Classes with constructor call this method every time a new object is created. Therefore, constructor is suitable for initializing objects before they are used.

In Php4, the constructor name is the same as the class name. Considering that calling the parent class constructor from the subclass constructor is very common, changes to the parent class caused by moving a class from an inheritance system often lead to the need to change the class's constructor. php4's approach is obviously not reasonable.

Php5 introduces a standard method for declaring BUILD functions: _ construct:

Example
<? Php
Class BaseClass {
Function _ construct (){
Print "In BaseClass constructor \ n ";
}
}

Class SubClass extends BaseClass {
Function _ construct (){
Parent: :__ construct ();
Print "In SubClass constructor \ n ";
}
}

$ Obj = new BaseClass ();
$ Obj = new SubClass ();
?>

To maintain backward compatibility, if php5 cannot find _ construct (), it will look for an old-fashioned constructor, that is, a method with the same name as the class. Simply put, there is a compatibility problem only when the old code contains a _ construct () method.

Analysis Method
It is very useful to define the Destructor for object-oriented programming. The Destructor can be used to record debugging information, close database connections, and so on to clear the final tasks. There is no destructor in Php4, although php4 already supports registering a function to be called at the end of the request.

The concept of the Destructor introduced by Php5 is consistent with that of other object-oriented languages (such as java. When the last reference pointing to this object is destroyed, the Destructor is called and the memory is released after the call is completed. Note: The Destructor does not accept any parameters.

Example
<? Php
Class MyDestructableClass {
Function _ construct (){
Print "In constructor \ n ";
$ This-> name = "MyDestructableClass ";
}

Function _ destruct (){
Print "Destroying". $ this-> name. "\ n ";
}
}

$ Obj = new MyDestructableClass ();
?>

Like the build method, the parent class's destructor will not be implicitly called. Subclass can explicitly call parent ::__ destruct () in its own destructor.

Constants
Php5 introduces class-level constants.

<? Php
Class Foo {
Const constant = "constant ";
}

Echo "Foo: constant =". Foo: constant. "\ n ";
?>

The old code that does not use const still runs normally.

Exceptions
Php4 has no exception Control. Php5 introduces exception Control Modes similar to other languages (java. Note that php5 supports capturing all exceptions, but does not support finally clauses.

In the catch Block, you can throw an exception again. There can also be multiple catch statements. In this case, the caught exceptions are compared from top to bottom and compared with the catch statements. The first type of catch statement will be executed. If no matching catch clause is found, search for the next try/catch statement. Exceptions that cannot be captured will be displayed. If an exception is caught, the program starts to execute the catch statement block.

Example
<? Php
Class MyException {
Function _ construct ($ exception ){
$ This-> exception = $ exception;
}

Function Display (){
Print "MyException: $ this-> exception \ n ";
}
}

Class MyExceptionFoo extends MyException {
Function _ construct ($ exception ){
$ This-> exception = $ exception;
}

Function Display (){
Print "MyException: $ this-> exception \ n ";
}
}

Try {
Throw new MyExceptionFoo ('hello ');
}
Catch (MyException $ exception ){
$ Exception-> Display ();
}
Catch (Exception $ exception ){
Echo $ exception;
}
?>

The preceding example shows that you can define an Exception class that does not inherit from Exception. However, it is best to inherit from Exception and define your own Exception. This is because the system's built-in Exception class can collect a lot of useful information, and the Exception class that does not inherit it will not get this information. The following php code imitates the built-in Exception class of the system. Annotations are added to each attribute. Each property has a getter. Because these getter methods are often called by the system, these methods are identified as final.

Example
<? Php
Class Exception {
Function _ construct (string $ message = NULL, int code = 0 ){
If (func_num_args ()){
$ This-> message = $ message;
}
$ This-> code = $ code;
$ This-> file = _ FILE __; // of throw clause
$ This-> line = _ LINE __; // of throw clause
$ This-> trace = debug_backtrace ();
$ This-> string = StringFormat ($ this );
}

Protected $ message = 'unknown exception'; // exception message
Protected $ code = 0; // user defined exception code
Protected $ file; // source filename of exception
Protected $ line; // source line of exception

Private $ trace; // backtrace of exception
Private $ string; // internal only !!

Final function getMessage (){
Return $ this-> message;
}
Final function getCode (){
Return $ this-> code;
}
Final function getFile (){
Return $ this-> file;
}
Final function getTrace (){
Return $ this-> trace;
}
Final function getTraceAsString (){
Return self: TraceFormat ($ this );
}
Function _ toString (){
Return $ this-> string;
}
Static private function StringFormat (Exception $ exception ){
//... A function not available in PHP scripts
// That returns all relevant information as a string
}
Static private function TraceFormat (Exception $ exception ){
//... A function not available in PHP scripts
// That returns the backtrace as a string
}
}
?>

If we define an Exception class that inherits from the Exception base class

No compatibility issues. The old code will not be affected by this feature.

Dereferencing objects returned from functions
Php4 cannot reference the objects returned by the function again to call the method of returning objects. php5 can.

<? Php
Class Circle {
Function draw (){
Print "Circle \ n ";
}
}

Class Square {
Function draw (){
Print "Square \ n ";
}
}

Function ShapeFactoryMethod ($ shape ){
Switch ($ shape ){
Case "Circle ":
Return new Circle ();
Case "Square ":
Return new Square ();
}
}

ShapeFactoryMethod ("Circle")-> draw ();
ShapeFactoryMethod ("Square")-> draw ();
?>

Static member variables can be initialized.
Example
<? Php
Class foo {
Static $ my_static = 5;
Public $ my_prop = 'bla ';
}

Print foo: $ my_static;
$ Obj = new foo;
Print $ obj-> my_prop;
?>

Static Method
PHP 5 introduces static methods that can call static methods without instantiating classes.

Example
<? Php
Class Foo {
Public static function aStaticMethod (){
//...
}
}

Foo: aStaticMethod ();
?>

The pseudo variable $ this cannot be used in static methods.

Instanceof
Php5 introduces the instanceof keyword, which can be used to test whether an object is an instance of a class, an instance of a derived class, or an interface.

Example
<? Php
Class baseClass {}

$ A = new baseClass;

If ($ a instanceof baseClass ){
Echo "Hello World ";
}
?>

Static function variables
Currently, static variables are processed in the compilation phase. Therefore, programmers can assign values to static variables by referencing them. This can improve performance. However, indirect reference to static variables cannot be used.

You can also set the default value for the function parameters passed by reference.

Example
<? Php
Function my_function (& $ var = null ){
If ($ var = null ){
Die ("$ var needs to have a value ");
}
}
?>

_ Autoload ()
_ Autoload () is automatically called when an undeclared class is initialized. The class name is automatically passed to the _ autoload () function. And _ autoload () only has such a unique parameter.

Example
<? Php
Function _ autoload ($ className ){
Include_once $ className. ". php ";
}

$ Object = new ClassName;
?>

Reload method calls and attribute access
Both method call and attribute access can be reloaded using the _ call, _ get () and _ set () methods.

Example: _ get () and _ set ()
<? Php
Class Setter {
Public $ n;
Public $ x = array ("a" => 1, "B" => 2, "c" => 3 );

Function _ get ($ nm ){
Print "Getting [$ nm] \ n ";

If (isset ($ this-> x [$ nm]) {
$ R = $ this-> x [$ nm];
Print "Returning: $ r \ n ";
Return $ r;
} Else {
Print "Nothing! \ N ";
}
}

Function _ set ($ nm, $ val ){
Print "Setting [$ nm] to $ val \ n ";

If (isset ($ this-> x [$ nm]) {
$ This-> x [$ nm] = $ val;
Print "OK! \ N ";
} Else {
Print "Not OK! \ N ";
}
}
}

$ Foo = new Setter ();
$ Foo-> n = 1;
$ Foo-> a = 100;
$ Foo-> a ++;
$ Foo-> z ++;
Var_dump ($ foo );
?>

Example: _ call ()
<? Php
Class Caller {
Private $ x = array (1, 2, 3 );

Function _ call ($ m, $ ){
Print "Method $ m called: \ n ";
Var_dump ($ );
Return $ this-> x;
}
}

$ Foo = new Caller ();
$ A = $ foo-& gt; test (1, "2", 3.4, true );
Var_dump ($ );
?>

Iteration
When using objects with foreach, the iteration method is overloaded. The default behavior is all attributes of the iteration class.

Example
<? Php
Class Foo {
Public $ x = 1;
Public $ y = 2;
}

$ Obj = new Foo;

Foreach ($ obj as $ prp_name => $ prop_value ){
// Using the property
}
?>

All objects of a class can be viewed iteratively. If this class implements an empty interface: Traversable. In other words, the class that implements the Traversable interface can be used with foreach.

The IteratorAggregate and Iterator interfaces allow you to specify how class objects are iterated in the code. The IteratorAggregate interface has a method: getIterator () must return an array

Example
<? Php
Class ObjectIterator implements Iterator {

Private $ obj;
Private $ num;

Function _ construct ($ obj ){
$ This-> obj = $ obj;
}
Function rewind (){
$ This-> num = 0;
}
Function valid (){
Return $ this-> num <$ this-> obj-> max;
}
Function key (){
Return $ this-> num;
}
Function current (){
Switch ($ this-> num ){
Case 0: return "1st ";
Case 1: return "2nd ";
Case 2: return "3rd ";
Default: return $ this-> num. "th ";
}
}
Function next (){
$ This-> num ++;
}
}

Class Object implements IteratorAggregate {

Public $ max = 3;

Function getIterator (){
Return new ObjectIterator ($ this );
}
}

$ Obj = new Object;

// This foreach...
Foreach ($ obj as $ key => $ val ){
Echo "$ key = $ val \ n ";
}

// Matches the following 7 lines with the for ctictive.
$ It = $ obj-> getIterator ();
For ($ it-> rewind (); $ it-> hasMore (); $ it-> next ){
$ Key = $ it-> current ();
$ Val = $ it-> key ();
Echo "$ key = $ val \ n ";
}
Unset ($ it );
?>

New _ toString Method
The overwrite _ toString method can be used to control the conversion from an object to a string.

Example
<? Php
Class Foo {
Function _ toString (){
Return "What ever ";
}
}

$ Obj = new Foo;

Echo $ obj; // call _ toString ()
?>

Reflection API
Php5 introduces a full set of reflection APIs to support reverse engineering of classes, interfaces, functions, and methods.

It also provides APIs to extract comments from programs. For more information about the reflection API, see here: http://sitten-polizei.de/php/reflection_api/docs/language.reflection.html

Example
<? Php
Class Foo {
Public $ prop;
Function Func ($ name ){
Echo "Hello $ name ";
}
}

Reflection_class: export ('foo ');
Reflection_object: export (new Foo );
Reflection_method: export ('foo', 'func ');
Reflection_property: export ('foo', 'prop ');
Reflection_extension: export ('standard ');
?>

New Memory Management Mechanism
Php5 has a new memory management mechanism that enables it to run more effectively in a multi-threaded environment. When allocating and releasing memory, mutex is no longer used to lock/unlock

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.