Programming Language - Mentor of your Computer

Page 238

PHP

234 5.3 and newer PHP gained support for closures. True anonymous functions are supported using the following syntax: function getAdder($x) { return function ($y) use ($x) { return $x + $y; }; } $adder = getAdder(8); echo $adder(2); // prints "10"

Here, getAdder() function creates a closure using parameter $x (keyword "use" forces getting variable from context), which takes additional argument $y and returns it to the caller. Such a function can be stored, given as the parameter to other functions, etc. For more details see Lambda functions and closures RFC [63]. The goto flow control device was made available in PHP 5.3 and is used as follows: function lock() { $file = fopen("file.txt","r+"); retry: if(flock($file,LOCK_EX)) { fwrite($file, "Success!"); fclose($file); return 0; } else goto retry; }

When lock() is called, PHP opens a file and tries to lock it. retry:, the target label, defines the point to which execution should return if flock() is unsuccessful and the goto retry; is called. goto is not unrestricted and requires that the target label be in the same file and context.

Objects Basic object-oriented programming functionality was added in PHP 3 and improved in PHP 4.[3] Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance.[64] In previous versions of PHP, objects were handled like value types.[64] The drawback of this method was that the whole object was copied when a variable was assigned or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value. PHP 5 introduced private and protected member variables and methods, along with abstract classes and final classes as well as abstract methods and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore, PHP 5 added interfaces and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.