Zend2's new function introduction After reading, the income is not shallow

zhaozj2021-02-16  101

Changes in PHP 5 / ZEND ENGINE II

By PHP.NET MARCH 22, 2004 Body, Center, TD, P, LI {Font-Family: Verdana, Arial, Helvetica, Sans-Serif; Font-size: 11px; Color: # 333333} ul {margin-left: 20 H2 {Font-Family: Arial, Helvetica, Sans-Serif; Font-size: 16px; Color: # 336699} h3 {font-family: Arial, Helvetica, Sans-Serif; Font-size: 14px; Color: # 333333} New Object ModelPrivate and Protected MembersPrivate and Protected MethodsAbstract Classes and MethodsInterfacesClass Type HintsfinalObject CloningUnified ConstructorsDestructorsConstantsExceptionsDereferencing Objects Returned from FunctionsStatic Member Variables of Static Classes Can Now be InitializedStatic MethodsinstanceofStatic Function VariablesParameters that are Passed by Reference to a Function May Now Have Default Values__autoload () Overloadable Method Calls and Property AccessesIterationNew __METHOD__ ConstantNew __toString () MethodReflection APINew Memory Manager New Object Model PHP's handling of objects has been completely rewritten, allowing for better performance and more f eatures. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or pass as a parameter to a method. In The New Approach, Objects Are Reference by Handle, And Not By Value (One Can Think of A Handle As An Object's Identifier). Many PHP Programmers Aren '

t even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications. Private and Protected Members PHP 5 introduces private and protected member variables, they allow you to define the visibility of class properties. Example Protected member variables can be accessed in classes extending the class they are declared in, whereas private member variables can only be accessed by the class they belong to. Hello; Print "Myclass :: Printhello ()". $ this-> bar; print "myclass :: printhello ()". $ this-> foo;}} class myclass2 extends myclass {protected $ foo; function Printhello () {Myclass :: Printhello (); / * Should Print * / Print "Myclass2 :: PrintHello ()". $ this-> hello; / * shouldn't print out anything * / print "Myclass2 :: PrintHello ()". $ this-> bar; / * Shouldn't Print (Not DECLARED) * / print "Myclass2 :: Print Hello ()". $ this-> foo; / * Should Print * /}} $ obj = new myclass (); print $ obj-> hello; / * shouth't print Out Anything * / print $ obj-> bar; / * shouldn't print out anything * / print $ obj-> foo; / * shouldn't print out anything * / $ obj-> printhello (); / * Should Print * / $ obj = new myclass2 (); print $ obj-> hello; / * shopn't print out anything * / print $ obj-> bar; / * shouth '

t print out anything * / print $ obj-> Foo; / * Should not print out anything * / $ obj-> printHello ();?> Private and Protected MethodsWith PHP 5, private and protected methods are also introduced Example <. ? php class Foo {private function aPrivateMethod () {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-> AprotacectedMethod ();}} $ o = new bar; $ o- > aPublicMethod ();?..> Old code that has no user-defined classes or functions named "public", "protected" or "private" should run without modifications abstract classes and Methods PHP 5 also introduces abstract classes and methods An abstract Method Only Declares The Method's Signature and Does Not Provide An Implementation. a Class That Contains Abstract Methods Needs To Be Declared Abstr . Act Example test ();?> abstract classes can not be instantiated Old code that has no user-defined classes or functions named 'abstract' should run without modifications Interfaces PHP 5 introduces interfaces A class may implement an arbitrary list... Of Interfaces. EXAMPLE

} Class MyException implements Throwable {public function getMessage () {// ...}}?> Old code that has no user-defined classes or functions named 'interface' or 'implements' should run without modifications. Class Type Hints While remaining loosely typed PHP 5 introduces the ability to use class type hints to declare the expected class of objects that are passed as parameters to a method Example A ($ b); $ A-> B);?> These Class Type Hints Are Not Checked Upon Compilation, AS Would Be The Case In A Typed Language, But During Runtime. This Means That: Is Equivalent TO: This syntax only applies to objects / classes, not built-in types final PHP 5 introduces the" final "keyword to declare final members and methods Methods and members declared final can not. Be overridden by sub-classes. EXAMPLE it is furthermore Possible to make this prevents a class from Being Specialized (IT Cannot) Be inherited by another class. There's no need to declare the methods of a final class themsels as final. EXAMPLE <

? Php final class Foo {// class definition} // the next line is impossible // class Bork extends Foo {}?> Properties can not be final. Old code that has no user-defined classes or functions named 'final' should run without modifications. Object Cloning PHP 4 offered no way a user could decide what copy constructor to run when an object is duplicated. During duplication, PHP 4 did a bit for bit copy making an identical replica of all the object's properties. Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object y ou want to create a new instance of this other object so that the replica has its own separate copy An object copy is created by calling the object's __clone () method: - __ clone ();. ? > WHEN THE Developer Asks to create a new copy of an object, php 5 Will Check if A __clone () Method Has Been Defined or Not NOT__Clone () Which Will Copy All of the Object '

s properties. If a __clone () method is defined, then it will be responsible to set the necessary properties in the created object. For convenience, the engine will supply a function that imports all of the properties from the source object, so that they can start with a by-value replica of the source object, and only override properties that need to be changed Example. id = self :: $ ID ;} function __clone () {$ this-> name = $ THAT-> Name; $ this-> address = "new york"; $ this-> id = self: $ ID ;}} $ obj = new Mycloneable (); $ obj-> name = "Hello"; $ obj-> address = "tel-aviv"; Print $ OBJ-> ID. "/ N"; $ obj = $ obj -> __clone (); print $ OBJ-> ID. "/ n"; Print $ OBJ-> Name. "/ n"; Print $ OBJ-> Address. "/ n";?>

Unified Constructors PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. With PHP 4, constructor methods were class methods that had the same name as the class itself. Since it is very common to call parent constructors from derived classes, the way PHP 4 worked made it a bit cumbersome to move classes around in a large class hierarchy. If a class is moved to reside under a different parent, the constructor name of that parent changes as well, and the code in the derived class that calls the parent constructor has to be modified. PHP 5 introduces a standard way of declaring constructor methods by calling them By the name __construct (). EXAMPLE >

For backwards compatibility, if PHP 5 can not find a __construct () function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct () which was used for different semantics. destructors Having the ability to define destructors for objects can be very useful. destructors can log messages for debugging, close database connections and do other clean-up work. No mechanism for object destructors existed in PHP 4, although PHP had already support for registering functions which should be run on request shutdown PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as Java:. When the last reference TO An Object Is Destroyed The Object's Destructor, Which is a class method named __destruct () That Receives No parameters, is Called Before The Object Is Freed from Memory. EXAMPLE name = "mydestructure __destructure";} function __destruct () {Print "destroying". $ This-> name. "/ N";}} obj = new MyDestructableClass ();?> Like constructors, parent destructors will not be called implicitly by the engine in order to run a parent destructor, one would have to explicitly call parent :: __ destruct () in the destructor body Constants PHP.. 5 Introduces Per-Class Constants: >

Old code that has no user-defined classes or functions named 'const' will run without modifications. Exceptions PHP 4 had no exception handling. PHP 5 introduces a exception model similar to that of other programming languages. Note that there is support for "catch all "but not for the" finally "clause. Exceptions can be rethrown in catch blocks. Also it is possible to have multiple catch blocks. in that case the caught exception is compared with the classtype of each catch block from top to bottom and the first block that has an 'instanceof' match gets executed. When the catch block finishes, execution continues at the end of the last catch block. If no catch block has an 'instanceof' match then the next try / catch block is searched until no more try / catch blocks are available. In that case the exception is an uncaught exception and the program terminates with showing the exception. Example exception = $ exce ption;} 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;

t inherit from Exception it is best to do so. This is because the internal Exception class can gather a lot of information otherwise not available. The PHP code emulation code would look something like shown below. The comments show the meaning of each property and hence their getter methods. As the code shows it is possible to read any available information by using the getter methods. But since some of the methods are used internally they are marked final. All in all the class is very restrictive because it must be ensured that anything used internally always works as expected 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 = 'u nknown 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 GetTracesstring () {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 you derive your exception classes from this Exception base class your exceptions will be nicely shown in the built-in handler for uncaught exceptions. Old code that has no user-defined classes or functions 'catch', 'throw' and 'try' will run without modifications. dereferencing Objects Returned from Functions in PHP 4 it was not possible to dereference objects returned by functions and make further method calls on those objects With PHP 5, the following is now possible: draw (); ShapeFactoryMethod ( "Square") -> draw ();??> static Member Variables of static Classes Can Now be Initialized Example my_prop;?> static methods php 5 Introduces the 'static'

keyword to declare a method static, thus callable from outside the object context Example. The pseudo variable $ this is not available inside a method that has been declared static. instanceof PHP 5 introduces the instanceof keyword, that allows you to ascertain whether or not an object is an instance of a class, or extends a class, or implements an interface. Example Static Function Variables statics are now treated at compile-time which allows developers to assign variables to statics by reference?. This change also greatly improves their performance but means that indirect references to statics will not work anymore. Parameters that are Passed by Reference to a function May Now Have Default Values ​​Example __autoload () The __autoload () interceptor function will be automatically called when an undeclared class is to be instantiated The name of that class will be passed to the __autoload. () interceptor function as its only argument Example. Overloadable Method Calls and Property Accesses Both method calls and property accesses Can be overloaded via the __call (), __get () and __set () method () eXample: __Get () and __set () 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 ($ 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); ?> Orthoferloaded Way When Used with foreach. The default behavior is to ipample over all proties. EXAMPLE $ Prop_Value) {// @@@@@@>>

Each class whose instances can be iterated with foreach should implement the empty interface Traversable. Hence any object that says it implements Traversable can be used with foreach. The interfaces IteratorAggregate and Iterator allows you to specify how class objects are iterated in PHP code. The first of them simply has a method getIterator () which must return an array or an object that either implements the interface Iterator or is instantiated from an internal class that can be iterated Example obj = $ obj;} function rebind () {$ this-> Num = 0;} function hasmore () {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: r ETURN $ 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 Directive. $ it = $ obj-> Getiterator (); for ($ it-> rewind (); $ it-> hasmore (); $ it-> next) {$ key = $ it-> current (); $ Val = $ it-> key (); echo "$ key = $ val / n";} unset ($ it);?>

The matching for directive is very interesting here since it shows the use of all abstract methods declared in the interfaces Iterator and IteratorAggregate respectively. New __METHOD__ Constant The new __METHOD__ pseudo constant shows the current class and method when used inside a method and the function when used Outside of a class. EXAMPLE New __toString () Method The new __toString () magic method allows you to overload the object to string conversion Example Reflection API PHP 5 Comes With A Complete Reflection API That Adds the Ability To Reverse-Engineer Classes , Interfaces, Functions and Methods as Well as Extensions. The Reflection . API also offers ways of getting doc comments for functions, classes and methods Nearly all aspects of object oriented code can be reflected by using the reflection API which is documented separately Example

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

New Post(0)