PHP5 New Features: More object-oriented PHP

xiaoxiao2021-03-06  39

Original connection (http://www.php.net/ze-engine-2.php)

The kernel of the PHP processing target portion is fully revisited, and more functions have also improved performance. In previous versions of PHP, how to handle objects and processing basic types (numbers, strings). In this way, the object will be completely copied when the object is assigned to a variable, or when the object passes the object. In the new version, the above operation will pass a reference (you can understand the reference to the identifier), not the value.

Many PHP programmers may even have not perceived the old object processing. In fact, most PHP applications can run well. Or just require little changes.

Private and protected members

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

example

Protected members can be accessed by subclasses, while private members can only be accessed by class itself.

Hello; Print "Myclass :: Printhello ()". $ This-> bar; print "Myclass :: printhello ()". $ This-> foo;}} MyClass2 extends MyClass {protected $ Foo; function printHello () {MyClass :: printHello (); / * Should print * / print "MyClass2 :: printHello ()" $ this-> Hello;. / * Should not print out anything * / Print "Myclass2 :: Printhello ()". $ This-> bar; / * ShouldN't Print (not Declared) * / print "Myclass2 :: PrintHello ()". $ This-> foo; / * Should Print * /}} $ Obj = new myclass (); print $ obj-> hello; / * shouldn't print out anything * / print $ obj-> bar; / * shopn't print out anything * / print $ obj- > Foo; / * shouldn't print out anything * / $ OBJ-> PrintHello (); / * shop print * / $ obj = new myclass2 (); print $ obj-> hello; / * sho Uldn't print out anything * / print $ obj-> bar; / * shouth't print out anything * / print $ obj-> foo; / * shouldn't print out anything * / $ obj-> printhello (); ?> Private method and protected method

PHP5 also introduces the concept of private methods and protected methods.

example:

APRIVATEMETHOD ();}} Class Bar Extends foo {public function apublicMethod () {echo "bar :: apublicMethod () Called./n"; $ this-> AprotacectedMethod ();}} $ o = new bar; $ o- > ApublicMethod ();?> The previous code that does not use the class, the code without access, protected, private can run without the change.

Abstract class and abstract method

PHP5 also introduces the concept of abstract classes and abstract methods. Abstract methods only declare the signature of the method does not provide its implementation. Classes containing abstract methods must be declared as abstract classes.

example:

? Test ();?>

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

interface

PHP5 introduces an interface. A class can implement multiple interfaces.

example:

The old code that is not using the interface can run without the change.

Types of category

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

EXAMPLE

A ($ b); $ A-> b ($ b);?>>>>>>>>>>

As with other strong type languages, the type of PHP5 class is inspected during operation instead of compilation. which is:

The same below:

This syntax is only available for classes, which does not apply to build Types of.

Final

PHP 5 introduces Final keywords to declare Final members and Final methods. Final members and Final methods cannot be covered by subclasses.

EXAMPLE

Further, declare the class into Final. Declaring classes into Final to prevent this class from being inherited. The method in the final class is fixed by Final, no need to declare once.

EXAMPLE

Attributes cannot be defined as Final.

The old code that did not use Final can run without the change.

Object clone

PHP4 does not provide a mechanism to let users define their own copying process of the Copy Constructor. PHP4 makes a binary copy, thus a very accurate copy of all the properties of the object.

All attributes of precise replication of objects may not be we have always wanted. There is an example of how we really need to copy the structure: such as an object A of GTK WINDOW. A holds all the resources it needs. When copying this GTK Window to Object B, we prefer to hold the new resource object. An example: The object A contains an object C, when you copy object a to the object C. We may want the object B to include a new object C Copy, not a reference to an object C. (Translator Note: Here is shallow cloning and deep cloning.)

The copy of the object is the __clone () method of the Clone object by Clone (Clon). The __clone method of the object cannot be called directly.

When developer creates a copy of the object, PHP5 will check if the __clone () method exists. If there is no existence, it will call the default __clone () method, copy all the properties of the object. If the __clone () method is already defined, the _clone () method is responsible for setting the properties of the new object. For the sake of convenience, Engine will repay all properties default. So in the __clone () method, you only need to overwrite the properties that need to be changed. as follows:

EXAMPLE

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 a class of constructors. Classs with constructor call this method at each time you create a new object, so the constructor is suitable for the initialization of the object before being used.

In PHP4, the name of the constructor and the name of the class. Considering that the case where the parent class constructor from the subclass structure is very common, the parent class change caused by the relocation of the class from one inheritance system often leads to a configuration method that needs to change classes. The PHP4 practice is obviously not too reasonable.

PHP5 introduces a standard method for declaring build functions: __contruct (). As follows:

EXAMPLE

?

To keep backward compatibility, if PHP5 can not find __construct (), it will look for old-fashioned constructor, that is, the same name as the class. Simply put, there is only one compatibility problem when it contains a __construct () method in the elder code.

Destructure method

For object-oriented programming, a destructual method can be defined a very useful function. The destructure method can be used to record the debugging information, turn off the database connection, etc. Some work for clearance. There is no description method in PHP4, although php4 has supported a function to register a function to be called at the end.

The concept of the destructive method introduced by PHP5 and other object-oriented languages ​​(such as Java) are consistent. When the last reference to this object is destroyed, the destructor is called, and the memory is released after the call is completed. Note: The destructure method does not accept any parameters.

EXAMPLE

name = "MyDestructableClass";} function __destruct () {print "Destroying" $ this-> name "/ n"..; }}} $ obj = new mydestructureableclass ();?>> and build methods, the destructual method of the parent class will not be invoified. Subclasses can explicitly call it by calling parent :: __ destruct () in their own destructure.

Constants

PHP5 introduces a constant of Class level.

>

The old code that does not use const is still running normally.

EXCEPTIONS

PHP4 has no abnormal control. PHP5 introduces an exception control mode similar to other languages ​​(Java). It should be noted that PHP5 supports the capture of all exceptions, but does not support the finally clause.

In the Catch statement, you can re-throw an exception. There are also multiple catch statements, in which case, the captured exception compares and the catch statement compared to the Catch statement, and the first type matches the catch statement will be executed. If you have been searching, you have not found a matching catch clause, look for the next TRY / CATCH statement. Finally, the exception that cannot be captured will be displayed. If the exception is captured, the program will then start below the CATCH statement.

EXAMPLE

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 above example shows that you can define an exception class that does not inherit from Exception, but it is best to inherit from Exception and define your own exception. This is because the system built-in Exception class can collected a lot of useful information, without inheriting its exception class is not available. The following PHP code imitates the system built-in Exception class. Annotation is added behind each attribute. Each attribute has a getter, since these getter methods are often handled by the internal processing, so these methods are indicated by Final.

EXAMPLE

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?> If we define an exception class is inherited from an Exception base class

No compliance problem. The old code will not be affected by this feature.

Dereferencing Objects Returned from functions

The object returned in PHP4 cannot reference the function returned to the object to return to the object, and PHP5 is ok.

DRAW (); ShapeFactoryMethod ("Square" -> DRAW ();?> Static state Member variables can be initialized.

EXAMPLE

my_prop;?>>

Static method

PHP 5 introduces a static method that calls a static method in the case of non-instantiating classes.

EXAMPLE

>

Pseudo Variables $ this cannot be used in a static method method.

INSTANCEOF

PHP5 introduces InstanceOf keywords, allowing it to test an object is an instance of a class, or an instance of a derived class, or an interface is implemented

EXAMPLE

Static Function Variables

Now, static variables are handled in compilation phase. Therefore, the programmer can assign a value by reference to static variables. This can improve performance, but it is not possible to use indirect reference to static variables.

The function parameters passed by reference can now set the default.

EXAMPLE

__AUTOLOAD ()

__autoload () intercepting function is automatically called when an unspecified class is initialized. The name of this class will be automatically passed to the __autoload () function. __Autoload () is only such a unique parameter.

EXAMPLE

>

Overloaded method call and attribute access

Method call and attribute access can be overloaded by __call, __get () and __set () method.

EXample: __get () and __set ()

1, "b" => 2, "c" => 3); function __get ($ nm) {print "getting [$ nm ] / n "; if ($ this-> x [$ nm])) {$ r = $ this-> x [$ nm]; print" returning: $ r / n "; returnid $ 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 ()

x;}} $ foo = new caller (); $ a = $ foo-> test (1, "2", 3.4, true); var_dump ($ a);?>

Iterative

When using objects with Foreach, iterative is overloaded. The default behavior is all attributes of iterative classes.

EXAMPLE

$ Prop_Value) {// useing the profy}?>

All objects of a class can be iterated to browse, if this class implements an empty interface: TraveSable. In other words, the class that implements the Traversable interface can be used with Foreach.

Interface IteratorAggRegate and Iterator allow the specified object to be iterated in the code. There is a method for the IteratorAggregate interface: getItemrator () must return an array

EXAMPLE

obj = $ obj;} function rebind () {$ this-> Num = 0;} function valid () {RETURN $ THIS-> Num <$ this-> obj-> max;} function key () {return $ this-> num;} function current () {switch ($ this-> num) {casse 0: return " 1st "; Case 1: Return" 2nd "; Case 2: Return" 3rd "; default: return $ this-> Num." Th ";}} function next ()}}} function next ()}}}}}} Iteratraaggregate {public $ max = 3; function getiterator () {return new objectector ($ this);}} $ obj = new object; // this foreach ... foreach ($ OBJ AS $ Key => $ VAL) {Echo "$ Key = $ VAL / N";} // matches the folload 7 Lines with the for directive. $ it = $ obj-> Getiterator (); for ($ it); $ it-> hasmore ); $ it-> next-> current (); $ val = $ it-> key (); echo "$ key = $ val / n";} unset ($ it);? > New __tostri NG method

You can control the transition of the object to the string by overwriting the __toString method.

EXAMPLE

REFLECTION API

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

It also provides an API to extract an comment document from a program. Details of the API Reference Reference: http://sitten-polizei.de/php/reflection_api/docs/language.reflection.html

EXAMPLE

New Memory Management Mechanism

PHP5 has a new memory management mechanism such that it can run more efficiently in multi-threaded environments. When allocating and release memory, the MUTEX lock / release lock is no longer

转载请注明原文地址:https://www.9cbs.com/read-63788.html

New Post(0)