AD

PHP 5.3 New Features Summary

I. Introduction As early as the release of PHP5 object-oriented programming (OOP) and design made great progress, it offers many new features, such as the visibility of the class, class reflections. Can say for the PHP Object Oriented Programming has made an indelible contribution. PHP V5.3 provide a great deal in OOP complement, its release is designed to develop staff to do in the future use of the PHP V6 Zhunbei, known as the "only Queshao primary health Unicode Zhichi of PHP V6", it Increase some new Texing , removed some PHP versions in the future will not feature again, doing coolPHP development, the author summarizes the actual use of some PHP5.3 new features, this is gossip of a summary Bale ...

Second, new features
A new magic method __callStatic ()
About this method before, it is necessary to know as well as static methods and member variables in PHP5 magic method. Early on in PHP V4 to support static methods and class members to visit, but it can not Will method or as a specialist, designated for Jingtai visit the properties, such as in PHP V4 in
<?php
class Test {
   var $name;

   function Test(){
        $this->name = 'kokko';
   }

   function static1() {
       return '1';
   }

   function static2() {
       //   In PHP5, we use  self::static1()  Call the dynamic method  
       return Test::static1() . ' and 2';
   }
}

//  Now the way we use the static method call  ,  Will return  '1 and 2'
echo Test::static2();
?> 

  We can use the static method call  Test::static2(),  Without the need to declare a static access to addItem  ,  In PHP V5, we can the methods and member variables declared as static  ,  We can change the above code  
<?php
class Test {
   static $name = 'kokko';

   static function static1() {
       return '1';
   }
   static function static2() {
       //   In PHP5, we use  self::static1()  Call the dynamic method  
       return self::static1() . ' and 2';
   }
}

//  Now the way we use the static method call  ,  Will return  '1 and 2'
echo Test::static2();
?> 

PHP5  Not only provided in the definition of static variables, but also provides many  Magic Methods(  Magic Methods  ),  The introduction provides a magic methods  (  Such as  __call)  Support overloaded methods  (JAVA  Developers are familiar with this concept, is a method allows many different types of parameters  )  And multi-state support, which greatly enriched the  OOP  Programming methods, making  PHP  Can also use a variety of design patterns  Coding(  I remember long ago someone asked me the book Head First Design Patterns in ducks  PHP  Achieve up  ?).  In PHP V5.3 added a surname in magic methods  :__callStatic(),  Way his work  __call()  Not much difference between magic methods  ,__call()  It is designed to handle those who are not defined in the class or classes are not visible on the method call and students, and  __callStatic  Static method is used to process the call, it can provide a better way of method overloading  .  Such as  :
  Call functions in the name space  

<?php 
namespace comm; 
function doSomething(){
    echo "comm.doSomthing";
}
?> 
 
<?php 
namespace user; 
function doSomething(){
    echo "user.doSomthing";
}
?> 
 
<?php 
include 'comm.php'; 
use comm; 
doSomething(); // outputs "comm.doSomthing"; 
?> 
<?php 

include 'comm.php';
include 'user.php';
comm\doSomething(); // outputs "comm.doSomthing";
user\doSomething(); // outputs "user.doSomthing";
?>
class Test{
        public static function __callStatic( $name,$args ){
                return "  Static calls  {$name}  Methods  !";
        }

        public function __call($name,$args){
                return "  Call  {$name}  Methods  ";
        }
}

echo Test::getItem(1);  //  Output 'static call  getItem  Methods  !'
$test = new Test();
$test->getItem(1);   //  Out 'calls  getItem  Methods  !'
2.  Call the static method and dynamic member variables  

<?php
class Test 
{ 
    public static $name = 'kokko';

        public static function doTest() 
    { 
         return 'testing...';
    } 
} 

$class = 'Test'; 
$action = 'doTest'; 
$name = '$name';

//  Output   "testing..." 
echo Test::$action();  
//  Output    'kokko'
echo Test::$name;  
//  Output   "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' in E:\eusite\php3\test.php on line 13" 
echo $class::$action();
//  Output   "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' in E:\eusite\php3\test.php on line 20" 
echo $class::$name;  
?> 
  In the previous version of PHP is not variable by variable  (  You can use the string value to a variable specifies the name of another variable  )  Invoke the static method, PHP V5.3 added the dynamic properties of static method calls  ,  We can now use  $class::$action()  Invoke the static method of the  .


3. New features to give static keyword static binding to achieve delay
<?php
class Test 
{ 
    public static $name = 'kokko';

        public static function doTest() 
    { 
         return self::$name;
    } 
} 

class Test2 extends Test{
        public static $name = 'kokko won';
}

//  Output  kokko
echo Test2::doTest();
?> 
  I had the code of the output 'kokko won', but in fact counterproductive  ,doTest  Method call  self::$name  Because it is done in the Test class  ,  So the output is 'kokko', we want to achieve their goals only in the sub-class coverage  doTest  Static method,  PHP V5.3   Which gives the new features of the keyword static  ,  Allowed to reference the current class  :

<?php
class Test 
{ 
    public static $name = 'kokko';

        public static function doTest() 
    { 
         return static::$name;
    } 
} 

class Test2 extends Test{
        public static $name = 'kokko won';
}

//  Output  kokko won
echo Test2::doTest();
?> 
4.  SPL new data structure class and iterator class  

Standard PHP Library (Standard PHP Library,SPL) PHP V5 is in the new set of interfaces and classes ,PHP V5.3 Continue to expand, adding more classes , For example SplDoublyLinkedList class to provide support for dual-linked list :SplStack Support the realization of the heap :SplQueue Support the realization of the queue :SplFixedArray Implement a fixed-size array (PHP The default size of the array is variable ), The data structure is fixed size, and does not allow non-numeric index (NO $arr['kokko']), Its performance is very fast, said array of faster than the standard built-in 10% To 30%, I test it, it will be a 1000 Array element comparison is faster 20% About ( The results are related or more machines, I just bought the books soon )! In addition the standard library, and also added FilesystemIterator GlobIterator Other iterator class. More important point is PHP V5.3 Can not disable SPL support , What we should be able to see the point !
<?php
$stack = new SplStack(); 
$stack->push('kokko'); 
$stack->push('won'); 

//count   Can get the number of elements the heap  
echo count($stack); //   Output  2

//  Loop output elements  
foreach ( $stack as $item ) {
        echo $item."\n";
}

//   Stack, the output  won
echo $stack->pop();

//  Calculate the number of elements current heap  
echo count($stack); //   Output   1
?>
5.  Garbage collection and automatic memory deallocation  

My brother and write C C++, He saw me to write PHP, the variable never used the release of , He said that writing the code Zhenshuang so you do not worry about memory leaks ?
Similar with JAVA ,PHP There is a very simple garbage collector, its internal reference through a range of calculators on the object is no longer in the memory management garbage collection , When an object reference counter reaches 0 , Objects will be garbage collected and removed from memory, there is a problem in this way , If that exists between two objects reference each other relationship, such as " Parent - child objects ", In this case, even if the parent object is garbage collected , These calculators are not references to objects collected, these objects have to wait until after the completion of the script execution to be released , Even call the parent object unset() Will not release the child object the parent object in the memory reference . ( Reference **bugs.php**/bug.php?id=33595) Examples are as follows :
<?php
class A {
    public $b;

    function __construct () {
        $this->b = new B($this);
    }
}

class B {
    public $parent;

    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}

for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
}
?>
  The result is that I run  Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 32 bytes) in E:\eusite\php3\test.php on line 19

I modified the code as follows :
<?php
class A {
    function __construct () {
        $this->b = new B($this);
    }
}

class B {
    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}

for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
    unset($a);
}

//  Output is  :63,520.
echo number_format(memory_get_usage());
?>
  Here I manually unset way to release the parent object memory  ,  Seemingly I manually release the object memory, but if we change the test code follows  :

<?php
class A {
    function __construct () {
        $this->b = new B($this);
    }
}

class B {
    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}

for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
    unset($a);
    echo number_format(memory_get_usage()) . "<br>";
}
?>
  The output is as follows  :

62,400
62,800
63,176
63,552
...
33,550,992
33,551,368
33,551,744
33,552,120
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 42 bytes) in E:\eusite\php3\test.php on line 10
You will find the output value of one greater than, that we are in the unset When the object does not release the A class of B References to a class of memory, failing that , The output value should be the same .**bugs.php**/bug.php?id=33595 One solution mentioned :
<?php
class A {
    function __construct () {
        $this->b = new B($this);
    }

        function __destruct(){
                unset($this->b);
        }
}

class B {
    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}

for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
    $a->__destruct();
    unset($a);
    echo number_format(memory_get_usage()) . "<br>";
}
?>
  The output is as follows  :

63,496
63,496
...
63,496
63,496
end
63,496

In these circumstances created whenever an instance of class A and then out of memory the instance scope , Memory will not be released, so the script increase in memory use , Only the parent class to create a destructor will release the child object directly, this deconstruction of the lifting device must be called before the parent class reference , With the implementation of the code would be written C.C + + lacks a distinction between .
PHP V5.3 Solve this problem, the garbage collector will detect these circular reference , And can release the memory occupied by them, so when the script PHP Memory usage will remain steady. When A Each such reference is deleted, A class B Class reference will also be treated as garbage collection. This approach makes the garbage collection cycle PHP OOP The performance will be greatly enhanced, improving the memory usage to make indelible contributions .

6. Xin Tian closure and reflection as well as support for lambda functions
The JS programmer and front-end development Python And Ruby developers , These two should not be unfamiliar. Such as JavaScript Closure methods used in building the object. In PHP V3 Added support for closures and lambda , This means that functions can be dynamically created and passed as parameters to other methods .

1) Closure
By closure, we can further the logic encapsulated in a designated area , Binding within the context of a very small specific function. Written Ruby People should know the code in Ruby using the magic performance of closure , Here take a very practical example of .
<?php
class Logger{
        public static $mes = array();

        public static function log($code,$string){
                self::$mes[] = "[$code]:".$string; 
        }
}

class Blog{

        public function __construct(){
        }

        public function addComment($id,$data){
                $sql = sprintf( "INSERT INTO comments SET blog_id=%d,user_id=%d,content='%s'",$id,$data['user_id'],$data['content']);
                Logger::log('database',$sql);
                $sql = sprintf( "UPDATE blogs SET comments=comments+1 WHERE%d",$id );
                Logger::log('database',$sql);
                $sql = sprintf( "UPDATE users SET comments=comments+1 WHERE%d",$data['user_id'] );
                Logger::log('database',$sql);
        }
}

$blog = new Blog();
$blog->addComment(1,array(
        'user_id' => 1,
        'content' => 'hello',
));

print_r(Logger::$mes);
?>
  The code above, each log had to call  Logger::log  Static method, once  Logger::log  The parameters, we must change the code one by one one by one  ,  The following switch closure means to achieve the logging methods of the package to its range of addComment  .

<?php
class Logger{
        public static $mes = array();

        public static function log($code,$string){
                self::$mes[] = "[$code]:".$string; 
        }
}

class Blog{

        public function __construct(){
        }

        public function addComment($id,$data){
                $code = 'database';
                $log = function ($sql) use ($code) { Logger::log($code,$sql); };
                $sql = sprintf( "INSERT INTO comments SET blog_id=%d,user_id=%d,content='%s'",$id,$data['user_id'],$data['content']);
                $log($sql);
                $sql = sprintf( "UPDATE blogs SET comments=comments+1 WHERE%d",$id );
                $log($sql);
                $sql = sprintf( "UPDATE users SET comments=comments+1 WHERE%d",$data['user_id'] );
                $log($sql);
        }
}

$blog = new Blog();
$blog->addComment(1,array(
        'user_id' => 1,
        'content' => 'hello',
));

print_r(Logger::$mes);
?>
  Closure can also be used in the class object, the class is basically the definition of closure in the closure of an object defined outside the same  ,  The only difference is that through the   $this   Variable is automatically imported object, we can by the closure of the class  $this->name  Ways to access the class member variable name  :  We can also be defined as static closure closure, such closure is defined with the class distinction is that the latter will no longer be  $this  Variables passed to the closure. Such as  :

<?php
class Test{
        $name = 'kokko';

        function doAct($act){
                return function() use $act{
                        return $act.','.$this->name;
                }
        }
}

$test = new Test();
echo $test->doAct('hi');     //  Output  hi,kokko
?>
  If the closure function by adding  static  Keyword  'return static function() user $act',  Then the closure will not be able to access the code in the class Test  name  Property, and usually do not use the class itself only in the case of members of the property before the closure declaration  static  Static closure, because it does not apply to import the object closure  ,  Save memory. We can   __invoke()   Method to the class itself as a closure  .

<?php
class Test
{
    public function __invoke()
    {
         return "Hi,I am kokko";
    }
}

$test = new Test();
echo $test();   //  Output  'Hi,I am kokko'
?>
2)lambda  Function  

Commonly known as the anonymous function is defined simply abandoned at any time type function , Function itself exists only within the scope of variables defined function, so when the variable goes out of scope , Function also will be invalid, the function is somewhat similar to the meaning of local variables .
As early as we can, through PHP4 create_function To achieve the anonymous function, but the method and not very friendly , The package code is not suitable for many, interested friends can go and see PHP Relevant sections of the manual, and PHP V3 Started support for anonymous functions, anonymous functions we used a way to achieve great changes have .
<?php
$av = array("the ", "a ", "that ", "this ");
$fcstr = '$v = $v . "mango";';
array_walk($av, create_function('&$v,$k',$fcstr ));
print_r($av); 
?>
  If code exists in the create_function function slightly more complex logic  ,  Such as get a few if else, this code is quite inconvenient  ,PHP V5.3  We can write  :

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av,function(&$v,$k){
        $v = $v.'mango';
});
print_r($av); 
?>
  Code readability more, if the code appears if.else  Judge would not have a code such as the inconvenience  .


3) Reflection
JAVA Programmers should be familiar with the term reflection, and now PHP V5.3 Method also supports object reflection and reflection, which allows us to class . Interface. Functions and methods to perform reverse engineering . We ReflectionMethod and ReflectionFunction. ReflectionClass Class getClosure() Ways to achieve class. Function method of reverse engineering .
<?php
class Test{
        public $name = 'kokko';

        public function setName($name){
                $this->name = $name;
        }

        public function getName(){
                return $this->name;
        }
}
$class = new ReflectionClass('Test');
$method = $class->getMethod('getName');
$closure = $method->getClosure();
echo $closure();        //output 'kokko'
$class->setName('won');
echo $closure();        //output 'won'
?>
  Through reflection we can access the private class method can be introspective closure  ,  Through the reflection API to dynamically create functions and methods of existing closure  ,  So as to provide strong support for the closure  .

<?php
$closure = function ($x, $y = 1) {}; 
$m = new ReflectionMethod($closure); 
Reflection::export ($m);
//output
/*
Method [ <internal> public method __invoke ] {
  - Parameters [2] {
    Parameter #0 [ <required> $x ]
    Parameter #1 [ <optional> $y ]
  }
}
*/
?>
7.goto  Support  

PHP V5.3 Added in like VB goto Skip directly support the implementation of a code
<?php
$headers = Array('subject', 'bcc', 'to', 'cc', 'date', 'sender');
$position = 0;

hIterator: {
    $c = 0;
    echo $headers[$position] . PHP_EOL;

    cIterator: {
        echo ' ' . $headers[$position][$c] . PHP_EOL;

        if(!isset($headers[$position][++$c])) {
            goto cIteratorExit;
        }
        goto cIterator;
    }

    cIteratorExit: {
        if(isset($headers[++$position])) {
            goto hIterator;
        }
    }
}
?>
8.  Namespace  

PHP 5.3 OOP to begin a more comprehensive support , To help organize a large code base, add namespace Keyword support namespaces. We can namespace To declare a name space to better organize our code, and will not cause naming conflicts class , Note that namespace declaration must be the file or output the first command .
<?php 
namespace core; 
class app {
} 
?> 
  Use the code with the name of the space  

<coolcode lang="php" download="app.php">
<?php
namespace eu;
include('core/app.php');
class App extends core\App{
}
?>


9, using the Phar archive
The concept of Phar archive JAR file from Java, it allows the use of a single file packaged applications, this file contains the application needed to run everything. On the characteristics of CoolPHP not involved in the related applications, so do not do more is an example of. Interested friends can Google about, there should be a lot of information!

Original: ****kokkowon**/archives/902
标签: quot, member variables, object oriented programming, static methods, new features, return test, class test, complement, class members, additem, oop, static name, primary health, php versions, texing, php class, v5, echo test, indelible contribution, features summary
分类: PHP
时间: 2010-06-27

相关文章

  1. zookeeper features (summary)

    ** Refer to zookeeper 3.2.2 ** see also: http://leibnitz.iteye.com/blog/908805
  2. OFBiz list of features

    OFBiz list of features common functions * Free open source software o no royalties or copyright fees to mainta ...
  3. Under the Edit in intellij idea jspx files (change)

    Under the Edit in intellij idea jspx files (change) JSP 2.0 jspx is an important function in the upgrade, jspx ...
  4. High Class Properties

    Said begin to review the basis, though notes previously done, and now belongs to review, in considering whethe ...
  5. TOAD Getting Started

    Always wanted to learn under Oracle, frustration is not always a smooth installation. I later found is that th ...
  6. Windows2008初次体验的几个心得图文

    终于下定决心,把家里笔记本的操作系统装成了Win2008.(Windows Server 2008 June 2007 CTP).在安装使用中,碰到了一系列的问题,特整理如下,避免后来者被这些问题所阻挡. 一.Win20 ...
  7. Fundamentals - the concept of summary (JVM related. Jdk1.5 than the 1.4 new features. HashMap with HashTabel difference ......)

    Useful interview 1, JVM brief description (1) When running a java program that is running a java virtual machi ...
  8. Summary statistics and other features exist a large amount of data optimization report

    For a large amount of data, multi-group of the summary report does not use tabs, you can use the following opt ...
  9. [Change] EXT object-oriented features in summary

    1. Namespace: The definition of the class means Extjs code: Ext.namespace ("org.bestupon"); java cod ...
  10. Summary of the OOP features Alan Kay

    1, everything is an object. 2, calculated by objects communicate with each other, the request to perform actio ...
  11. Moodle features plug-in Summary

    Moodle official provide 654 kinds of plug-ins or modules moodle.org The original plate: 1. Html templates 2. S ...
  12. Summary of design

    Abstract: This article is a summary of the design at the practice and study some of the experiences with the s ...
  13. Servlet 2.5 new features

    September 26, 2005, Sun Company and the JSR154 Expert Group on Servlet API released a new version. Under norma ...
  14. Mantis maintenance project summary

    Maintaining the company's recent Mantis, done several times before adjustment, are different, this project obv ...
  15. A software engineer summary of 6 years

    "And upon graduation a year" to see groups of students to leave the ivory tower life and embark on t ...
  16. Spring2.5 new features

    Spring2.5 listed here, we only used the need to pay attention to new features, Source is the official Spring2. ...
  17. jQuery grammar summary and Notes

    1, Introduction 1.1, an overview of WEB2.0 and ajax with the idea at the rapid development of Internet communi ...
  18. Overview Summary of the design of how to do that - the design of structured methods and object-oriented design methods

    Overview Summary of the design of how to do that - the design of structured methods and object-oriented design ...
  19. Flex3.0 new features 2 ---- Flex-Ajax Bridge

    23.5 the use of Flex-Ajax Bridge Technology Control Flex application The previous section describes how Flex t ...