Home Backend Development PHP Tutorial PHP 5 was grandly launched yesterday--new features of PHP 5/Zend Engine 2.0_PHP Tutorial

PHP 5 was grandly launched yesterday--new features of PHP 5/Zend Engine 2.0_PHP Tutorial

Jul 21, 2016 pm 04:10 PM
php zend Preface new features yesterday characteristic Sudden


Preface

Today I suddenly thought of browsing the official PHP website and saw the announcement of the launch of PHP5 at a glance. Although I have seen the preview of PHP5 before, I still carefully read the article on new features of PHP 5/Zend Engine 2.0, and a breath of JAVA came to my face...
I specially translated this article and first published it on the CSDN website. For the enjoyment of readers.

New features of PHP 5/Zend Engine 2.0
Translated by Xu Huanchun sfwebsite@hotmail.com
http://www.php.net/zend-engine-2.php

New Object Model
The object handling part in PHP has been completely rewritten with better performance and more features. In previous versions of PHP, objects were treated the same as built-in variable types (such as integer and string). The disadvantage was that when a variable was assigned to an object or an object was passed as a parameter, you got a copy of the object. In the new version, an object is referenced by its handle, not by its value. (A handle can be thought of as an identifier of an object)
Many PHP programmers may not be aware of the "copy quirks" of the previous object model, so previous PHP programs will not need to make any changes, or only small changes The changes will work
Private and protected members
PHP 5 introduces private and protected member variables, which can define when class properties can be accessed.
Example
Protected member variables of a class can be accessed in extended classes of this class, while private member variables can only be accessed in this class.
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;
                                                                                                                                                                                                                                 . > protected $Foo;

function printHello() {
MyClass::printHello(); /* Should print */
print "MyClass2::printHello() " . gt; Hello; /* Shouldn't print out anything */
                                                                                                                                                                                                . ::printHello() " . $this->Foo; /* Should 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(); /* Should 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
In PHP 5 (ZEND Engine 2), private and protected methods were also introduced.
Example:
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->aProtectedMethod();
}
}

$o = new Bar;
$o->aPublicMethod();
?>
Although "public" is not defined in the user-defined classes or methods in the previous code ," keywords such as "protected" or "private", but can be run without editing.
Abstract classes and methods
PHP 5 also introduces abstract classes and methods. Abstract methods only declare method definitions and do not provide actual execution. Classes containing abstract methods need to be declared as abstract classes.
Example:
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. Although the "abstract" keyword is not defined in the user-defined classes or methods in the previous code, it can be run without editing.
Interface
ZEND Engine 2.0 introduces interface. A class can run any arbitrary list of interfaces.
Example
Example:
interface Throwable {
public function getMessage();
}

class Exception implements Throwable {
public function getMessage() {
// ...
}
?>
Although the "interface" keyword is not defined in the user-defined classes or methods in the previous code, there is no need to edit it. Runnable.
Class type definition
While retaining classes without defining types, PHP 5 introduces class type definitions to declare which class you want to pass to a method through parameters.
Example
Example:
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);
?>
These class type definitions are not like some that require type pre-definition Languages ​​do not check at compile time, but at runtime. This means:
function foo(ClassName $object) {
// ...
}
?>
is equivalent to:
function foo($object) {
if (!($object instanceof ClassName)) {
die("Argument 1 must be an instance of ClassName");
}
}
?>
This syntax is only used for objects or classes, not for built-in types.

final
PHP 5 introduced the "final" keyword to define members or methods that cannot be overridden in subclasses.
Ex: 🎜>Although the "final" keyword is not defined in the user-defined classes or methods in the previous code, it can be run without editing.
Object Cloning
When an object is copied in PHP 4, the user cannot decide the copying mechanism. When copying, PHP 4 makes an exact copy of the original object, bit by bit.
We don’t have to build an exact replica every time. A good example of needing a copying mechanism is when you have an object representing a GTK window, which owns all the resources of that window. When you create a copy, you may need a new window that owns the original window. All properties, but requires owning the resources of the new window. Another example is if you have an object that references another object, and when you copy the parent object, you want to create a new instance of that referenced object so that the copy references it.
Copying an object is completed by calling the object's __clone() method:
$copy_of_object = $object->__clone();
?>
When a developer requests to create a new copy of an object, the ZEND engine checks whether the __clone() method is defined. If undefined, it calls a default __clone() method to copy all properties of the object. If this method is defined, it is responsible for setting the necessary properties in the copy. For convenience, the engine will provide a function to import all properties from the source object, so that it can first get a copy of the source object with values, and only need to overwrite the properties that need to be changed.
Example:
class MyCloneable {
static $id = 0;

function MyCloneable() {
$this->id = self: :$id++;
}

function __clone() {
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";
?>
Uniform constructor name
The ZEND engine allows developers to define the constructor method of a class. When a class with a constructor method is created, the constructor method will be called first. The constructor method is suitable for initialization before the class is officially used.
In PHP4, the name of the constructor is the same as the class name. Due to the common practice of calling parent classes in derived classes, PHP4 handles things a bit awkwardly when moving classes within a large class inheritance. When a derived class is moved to a different parent class, the constructor name of the parent class must be different. In this case, the statements about calling the parent class constructor in the derived class need to be rewritten.
PHP 5 introduces a standard way of declaring constructor methods by calling them by the name __construct().
PHP5 introduces a standard way of declaring constructor methods by calling them by the name __construct().
Example
class BaseClass {
function __construct() {
print "In BaseClass constructorn";
}
}

class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructorn";
}
}

$obj = new BaseClass();
$obj = new SubClass();
?>
For backward compatibility, when PHP5 cannot find the __construct() method in the class, it will use the old method, which is the class name to find the constructor. This means that the only possible compatibility issue is if a method name called __construct() has been used in previous code.
Destruction method
It is very useful to define the destruction method. The destructor method can record debugging information, close the database connection, and do other finishing work. There is no such mechanism in PHP 4, although PHP already supports registering functions that need to be run at the end of the request.
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 name %__destruct()% that recieves no parameters, is called before the object is freed from memory.
PHP5 introduces a destructor method similar to other object-oriented languages ​​such as Java: when the last reference to the object is cleared, the system will The destructor method named __destruct() is called before the memory is released.
Example:
class MyDestructableClass {
function __construct() {
print "In constructorn";
$this->name = "MyDestructableClass";
}

function __destruct() {
                                                                                                                                                                      new MyDestructableClass();
?>
Similar to the constructor method, the engine will not call the destructor method of the parent class. To call this method, you need to pass parent::__destruct in the destructor method of the subclass () statement to call.
Constant
PHP 5 introduces class constant definition:
class Foo {
const constant = "constant";
}

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

PHP5 allows expressions in constants, but expressions in constants will be evaluated at compile time., Therefore a constant cannot change its value on the fly.
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 classes or methods in the previous code, it can be run without editing.
Exceptions
PHP 4 had no exception handling. PHP 5 introduces an exception model similar to that of other programming languages.
Example:
class MyExceptionFoo extends Exception {
function __construct($exception) {
parent::__construct($exception);
}
}

try {
throw new MyExceptionFoo("Hello");
} catch (MyException $exception) {
print $exception->getMessage();
}
?>
Although the 'catch', 'throw' and 'try' keywords are not defined in the user-defined classes or methods in the previous code, they can be run without editing.
Function returns object value
In PHP 4 it wasn't possible to dereference objects returned by functions and make further method calls on those objects. With the advent of Zend Engine 2, the following is now possible:
In PHP4, it is impossible for a function to return the value of an object and make method calls on the returned object. Through ZEND engine 2, this becomes possible:
class Circle {
function draw () {
          print "Circlen"; >}

function ShapeFactoryMethod($shape) {
switch ($shape) {
case "Circle":
return new Circle();
case "Square":
          return new Square();
  }
}

ShapeFactoryMethod("Circle")->draw();
ShapeFactoryMethod("Square")->draw() ;
?>
Static member variables in static classes can now be initialized
Example
class foo {
static $my_static = 5;
}

print foo::$my_static;
?>
Static method
PHP5 introduced the keyword 'static' to define a static method, which can be called from outside the object.
Example:
class Foo {
public static function aStaticMethod() {
                    // ... Foo::aStaticMethod();
?>
The virtual variable $this has no effect in static methods.
instanceof
PHP5 introduced the keyword instanceof to determine whether an object is an instance of an object, a derivative of an object, or uses an interface.
Example:
class baseClass { }

$a = new baseClass;

if ($a instanceof basicClass) {
echo " Hello World";
}
?>
Static Function Variables
All static variables are now handled at compile time, allowing developers to specify static variables by reference. This change improves efficiency but means that indirect references to static variables are not possible.
Parameters passed by address in the function allow definition of default values
Example:
function my_function(&$var = null) {
if ($var == = null) {
die("$var needs to have a value");
}
}
?>
__autoload()
Initializing an undefined class , the engine will automatically call the __autoload() interceptor function. The class name will be passed to it as the only parameter to the __autoload() interceptor function.
Example:
function __autoload($className) {
include_once $className . ".php";
}

$object = new ClassName;
?>
Overloading of method and attribute calls
The general __call(), __get() and __set() methods can be overloaded for method and attribute calls.

例: __get() 和 __set()
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: $rn";
            return $r;
        } else {
            print "Nothing!n";
        }
    }

    function __set($nm, $val) {
        print "Setting [$nm] to $valn";

        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);
?>
例: __call()
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);
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/314178.htmlTechArticle前言 今天突然想到PHP官方网站上一转,一眼就看到PHP5推出的通告。虽然以前看到过PHP5的预告,但还是仔细看了PHP 5/Zend Engine 2.0新特性一文...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles