Improvements to PHP 5/zend Engine 2.0

Source: Internet
Author: User
Tags exception handling expression final functions getmessage object model variables zend
In the past two years did not use PHP to write the program, today to use PHP, on the internet to check, saw the PHP5, a momentary interest in the big up, so translated this article.
The article comes from http://www.php.net/.
The new object model
The object processing part of PHP has been completely rewritten, with better performance and more functionality. In previous versions of PHP, objects were treated as primitive simple types
(such as Integer and string), the disadvantage of this method is that when the variable is assigned or passed as a parameter, the object copy is obtained. And in the new version,
Objects are referenced through a handle, rather than through the object's value (the handle is imagined as an object's identifier).
Many PHP programmers may not realize the "copying quirks" of the old object model, so most of the previous PHP programs will not need to make any changes
You can run it, or make very few changes.

Private and protected members
PHP 5 introduces private and protected member variables that define visual class properties.
Example
Protected member variables can be accessed in subclasses of the class, while private member variables can only be accessed in the owning class.
<?phpclass MyClass {Private $Hello = "Hello, world!\n"; protected $Bar = "Hello, foo!\n"; protected $Foo = "Hello, Bar !\n "; function Printhello () {print "MyClass::p Rinthello ()". $this->hello; Print "MyClass::p Rinthello ()". $this->bar; Print "MyClass::p Rinthello ()". $this->foo; }}class MyClass2 extends MyClass {protected $Foo; function Printhello () {MyClass::p Rinthello ();/* Should Print/print "MyClass2::p Rinthello ()". $this->hello; /* shouldn ' t print out anything/print "MYCLASS2::p Rinthello ()". $this->bar; /* shouldn ' t print (not declared)/print "MyClass2::p Rinthello ()". $this->foo; /* Should print */}} $obj = new MyClass ();p rint $obj->hello; /* Do not output any content, the following similar */print $obj->bar; /* shouldn ' t print out anything */print $obj->foo; /* shouldn ' t print out anything */$obj->printhello (); /* Should Print */$obj = new MyClass2 ();p rint $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 Protection methods

In PHP 5 (Zend Engine 2), private methods and protection methods are also introduced.
Example:
<?phpclass Foo {Private Function Aprivatemethod () {echo "Foo::aprivatemethod () called.\n";} protected function Aprot Ectedmethod () {echo "Foo::aprotectedmethod () called.\n"; $this->aprivatemethod ();} Class Bar extends Foo {public Function Apublicmethod () {echo "Bar::apublicmethod () called.\n"; $this->aprotectedmetho D (); } $o = new Bar; $o->apublicmethod ();? >
The user-defined class or method in the previous code does not have a "public," "protected" or "private" keyword defined, but can be run without modification.

Abstract classes and methods
PHP 5 also introduces abstract classes and methods. An abstract method declares only the "symbol" of a method and does not provide its implementation. A class that contains abstract methods needs to be declared "abstract."
For example:
<?phpabstract class AbstractClass {abstract public Function test ();} Class Implementedclass extends AbstractClass {public Function test () {echo "implementedclass::test () called.\n";}} $o = new Implementedclass; $o->test (); >
An abstract class cannot be instantiated.
The "abstract" keyword is not defined in the user-defined class or method in the old code, but can be run without modification.
Interface (interfaces)
Zend Engine 2.0 introduces the interface. A class can implement any list of interfaces.
For example:
<?phpinterface throwable {public Function getMessage ();} Class Exception implements Throwable {public Function getMessage () {//...}? >
The "interface" keyword is not defined in the user-defined class or method in the old code, but can run correctly without modification.

Class type Hints
While the retention class does not need to define a type, PHP 5 introduces a class-type hint to declare, expecting the object's class to pass through arguments to a method.
For example:
<?phpinterface 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); >
These class-type hints are not checked in compilation, as in some languages that require a type definition, but are checked at run time. This means:
<?phpfunction foo (ClassName $object) {//...}? >
is equivalent to:
<?phpfunction foo ($object) {if (!) ( $object instanceof ClassName)) {die ("Argument 1 must is an instance of ClassName");}? >
This syntax is used only for objects or classes, not for builtin (built-in) types.

Final keyword (final)
PHP 5 Introduces the "final" keyword to define a member or method that cannot be overridden in a subclass.
Cases:
<?php
Class Foo {final function bar () {//...}}? >
The "final" keyword is not defined in user-defined classes or methods in previously written code, but can be run without modification.
Objects cloning (object cloning)
PHP 4 When an object is replicated, the user cannot judge which copy constructor is running. When replicating, PHP 4 is based on the properties of the object
One by one copies the same copy.
It's not always what we want to build an exact replica every time. An example of a good copy construct is when there is
An object that represents a GTK window that owns all the resources of the window, and when you create a copy you may need a
A new window that owns all the properties of the original window, but requires a resource that has a new window. Another example is that you have a
Object refers to another object, and when you copy the parent object, you want to create a new instance of the referenced object so that the replica has a separate copy.
The copy of an object is accomplished by calling the object's __clone () method:
<?php
$copy _of_object = $object->__clone ();
?>

When a developer requests a new copy of an object, the Zend engine checks to see if the __clone () method has been defined. If you do not define
, it invokes a default __clone () method to copy all the properties of the object. If the method is defined, the method is responsible for
Set the necessary properties in the copy. For ease of use, the engine provides a function to import all the properties from the source object so that it can
To get a copy of the source object with the value first, and then simply overwrite the property that needs to be changed.
Cases:
<?php
Class Mycloneable {
static $id = 0;

function mycloneable () {
$this->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 method of Construction
The Zend Engine allows developers to define how classes are constructed. A class that has a constructor method calls the constructor method first when it is new, constructs the
method is applicable to initialization before the class is formally used.
In PHP4, the constructor method has the same name as the class name. Because invoking the parent class in a derived class is more common, it results in
In PHP4, when a class moves in a large class inheritance, the processing is a bit clumsy. When a derived class is moved to a different
Parent class, the constructor method name of the parent class must be different, so that the statement in the derived class about invoking the parent class construction method needs to be overwritten.
PHP5 introduces a standard way of defining construction methods, defined by calling their __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 ();
?>

For backward compatibility, when the PHP5 class cannot find the __construct () method, it passes through the old method, which is the class name
To find the construction method. This means that the only possible compatibility problem is the one used in the previous code
A method name named __construct ().

destructor method
It is very useful to define a destructor method. The destructor can record debugging information, close the database connection, and do other cleanup
Job. There is no such mechanism in PHP4, although PHP has support for registering functions that need to be run at the end of a request.
PHP5 introduces a destructor similar to other object-oriented languages such as the Java language: When the last reference to that object is cleared,
The system will invoke the destructor named __destruct () before the object is released from memory.
Example:
<?php
Class Mydestructableclass {
function __construct () {
Print "in constructor\n";
$this->name = "Mydestructableclass";
}

function __destruct () {
Print "destroying". $this->name. "\ n";
}
}

$obj = new Mydestructableclass ();
?>

Similar to the construction method, the engine will not invoke the destructor of the parent class, and in order to invoke the method you need to
Class is invoked through the parent::__destruct () statement in the destructor method of the

Constant
PHP 5 introduces a class constant (Per-class constants) Definition:
<?php
Class Foo {
CONST CONSTANT = "constant";
}

echo "foo::constant =". Foo::constant. "\ n";
?>

PHP5 allows an expression to be included in a constant, but an expression in the compile-time literal is computed.
Therefore, a constant cannot change its value in operation.
<?php
Class Bar {
Const A = 1<<0;
Const B = 1<<1;
Const C = A | b
}
?>
Although the "const" keyword is not defined in the user-defined class or method in the previous code,
But you can run it without modification.

Exception (Exceptions)
There is no exception handling in PHP4, PHP5 introduces the exception handling model which is similar to other languages.
<?php
Class Myexceptionfoo extends Exception {
function __construct ($exception) {
Parent::__construct ($exception);
}
}

try {
throw new Myexceptionfoo ("Hello");
catch (Myexceptionfoo $exception) {
Print $exception->getmessage ();
}
?>

The ' catch ', ' throw ' and ' try ' keywords are not defined in the user-defined class or method in the previous code, but need not be modified
can be run.

function returns the value of an object
In PHP4, it is not possible for a function to return the value of an object and make a method call to the returned object, along with Zend Engine 2
(Zend Engine 2), the following calls are possible:
<?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 to New Square ();
}
}

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

Static member variables in static classes can be initialized
For example:
<?php
class Foo {
static $my _static = 5;
}

Print foo:: $my _static;
?>



static method (Methods)
PHP5 introduces the keyword ' static ' to define a static method that can be invoked from outside the object.
For example:

<?php
Class Foo {
public static function Astaticmethod () {
// ...
}
}

Foo::astaticmethod ();
?>

Virtual variable $this is not valid in a method that is defined as static (static).


instanceof

PHP5 introduces the "instanceof" keyword to determine whether an object is an instance of an object, or derives from an object, or uses an interface.

Example:

<?php
Class BaseClass {}

$a = new BaseClass;

if ($a instanceof Basicclass) {
echo "Hello World";
}
?>





static functions variable (static function variables)
All static variables are now processed at compile time, which allows developers to specify static variables by reference. This change increases efficiency but means it is not possible to indirectly reference static variables.


Parameters passed by reference in a function allow default values
For example:

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



__autoload ()



When an undefined class is initialized, the __autoload () intercept function (Interceptor function) is automatically tuned
Use. The class name is passed to it as the __autoload () block function unique argument.
For example:
<?php
function __autoload ($className) {
Include_once $className. ". PHP";
}

$object = new ClassName;
?>



Overloads of method and property calls
All method calls and property accesses can be overloaded by Universal __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 {
var $x = Array (1, 2, 3);

function __call ($m, $a) {
Print "Method $m called:\n";
Var_dump ($a);
return $this->x;
}
}

$foo = new Caller ();
$a = $foo->test (1, "2", 3.4, true);
Var_dump ($a);
?>



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.