Best For Interview , PHP4 , PHP5, PHP6 , PHP 4 vs 5 vs 6
PHP 4 and OOP ?
* Poor Object model
* Methods
o No visibility
o No abstracts, No final
o Static without declaration
* Properties
o No static properties
o No constants
* Inheritance
o No abstract, final inheritance, no interfaces
o No prototype checking, no types
* Object handling
o Copied by value
o No destructors
13 Jul 2004: PHP 5.0
* ��Completely rewritten ZendEngine 2.0
* ��First version with the new object model
* ��Libxml2 based XML replaces Sablotron
* ��New extensions
o ��DOM, MySQLi, PDO, SimpleXML, SPL
* ��Unbundled mysqlclient library
From engine overloading . . .
* ��Zend engine 2.0+ allows to overload the following
o ��by implementing interfaces
+ ��Foreachby implementing Iterator, IteratorAggregate
+ ��Array access by implementing ArrayAccess
+ ��Serializing by implementing Serializable
o ��by providing magic functions
+ ��Function invocation by method __call()
+ ��Property access by methods __get()and __set()
+ ��Automatic loading of classes by function __autoload()
* PHP4 safety modes for classes (public, private) are not accepted.
* The Zend Engine II with a new object model and dozens of new features.
* XML support has been completely redone in PHP 5, all extensions are now focused around the excellent libxml2 library (http://www.xmlsoft.org/).
* In PHP5 it is firstly checked if there is a function (method) __construct (). If it does not exist, check if there is a function (method) which has the same name as the class.
* The extension called dom_xml does not belong any more to PHP 5.
* New reserved names which appeared in PHP 5. (Exception, interface, try, abstract, catch, public, protected, private).
* A new MySQL extension named MySQLi for developers using MySQL 4.1 and later. This new extension includes an object-oriented interface in addition to a traditional interface; as well as support for many of MySQL's new features, such as prepared statements.
* SQLite has been bundled with PHP. For more information on SQLite, please visit their website.
* A brand new built-in SOAP extension for interoperability with Web Services.
* A new SimpleXML extension for easily accessing and manipulating XML as PHP objects. It can also interface with the DOM extension and vice-versa.
* Streams have been greatly improved, including the ability to access low-level socket operations on streams.
* PHP 5 comes with the introduction of exception handling, the Standard PHP Library (SPL), enhanced support for XML, reflection, and quite a few enhancements to the object oriented features of the language.
* PHP 5 comes with Much improved OOP system, including method/property visibility, destructors, autoloading, interfaces & abstraction
* PHP 5 comes with SPL - Standard PHP Library including iterators (object traversal) with support for arrays, XML data & directories.
* PHP 5 comes with Exception handling
* PHP5 Data Objects (PDO)
Here are some differences I've run into during a recent php4 to php5 conversion:
Constructors (+1 for php5)
php4: Constructors are named after their class. If you change the name of a class, you have to find all callers of the constructors. Ew!
php5: Constructors are named __construct. If no __construct method is found, falls back to php4 behavior.
Destructors (+1 for php5)
php4: No such concept.
php5: Destructors are named __destruct.
$this = new Class(...); (+2 for php4)
php4: $this can be reassigned, allowing one to change the class implementing an object. A very useful feature and one I used quite a lot.
php5: Assignment to $this is explicitly forbidden. Factory methods are the recommended substitute, but they're ugly.
array_shift($args = func_get_args()); (+1 for php4)
php4: If func_get_args() returns [a, b, c], $args is [b, c]--as expected.
php5: If func_get_args() returns [a, b, c], $args is [a, b, c]. Good luck hunting down that bug.
Copying through Assignment (+1 for php4)
$o1 = new Object(...); $o2 = $o1;
$o1->setThing('x'); $o2->setThing('y');
php4: $o1 and $o2 are different objects, with Thing set to 'x' and 'y', respectively. This behavior matches that of strings, numbers, and other non-object types, which are also copied on assignment.
php5: $o1 and $o2 are the same object, with Thing set to 'y'. This behavior contradicts that of strings, numbers, and other non-object types which do produce copies. A clone operator was introduced to work around this (provided your objects also implement __clone methods); however, the clone operator only works on objects, not strings or numbers, so ensuring you've produced a copy is now along the lines of $o2 = is_object($o1) ? clone $o1 : $o1;. Ick.
And some differences which might get used now that I've transitioned to php5:
Public, Protected, Private Class Variables (no point)
php4: All class variables are public.
php5: Class variables can have differing access levels. This annoys me, but some people like it.
Class Constants (+0.5 for php5)
php4: No such thing. I work around this, and the lack of namespacing in general, by using Class__CONSTANT.
php5: Has them as Class::CONSTANT. It isn't namespace support, and has quite a few caveats, but it's sort of an improvement if you squint just right.
Autoloading (+1 for php5)
php4: No such thing. If you want to load classes, you'd better make sure there are require_once statements all over the place. Or write an object-creation function (make_instance) which automatically loads any class that doesn't exist. make_instance('Class', ...) isn't nearly as pretty as new Class(...), though.
php5: Autoloading exists, provided you write an __autoload function. No more does require_once need to be littered around one's code. A marginal savings overall, but still an improvement.
PHP developers, like all developers, want their scripts to be as compatible as possible. Often, this involves looking into the past, to see if scripts are backwards-compatible. But, we sometimes have to look into the future - to see what is changing, and to understand what we need to do to become compatible.
PHP6 is the latest, yet unreleased version of PHP. It is still under development and won't be released for some time yet. Nonetheless, it is still important that we consider the changes we know about at the moment, and write scripts which are compatible.
If you want to make use of PHP6 when it comes, you're going to have to write your new scripts so they are compatible, and possibly change some of your existing scripts. To start making your scripts PHP6 compatible, I've compiled a list of tips to follow when scripting:
Don't use register_globals
In PHP6, support for register_globals will be no more. There will be no option to turn it on or off - it will not exist. This change should not affect you, as you shouldn't really use register_globals anyway. If you don't already know, register_globals puts $_REQUEST into the global scope, so you can access the variables just like any other variable. Instead, you should access inputted data like this:
$_GET['input'];
$_POST['input'];
$_REQUEST['input'];
Stop using magic_quotes
In my opinion, this tip should be applied whether you are using PHP 3, 4 or 5. Thankfully, in PHP6, the magic_quotes feature is going to disappear with register_globals. For those who don't know, magic_quotes automatically escapes single quotes, double quotes, backslashes, and NULL characters.
Don't Register Long Arrays
If you access user inputted data using $HTTP_POST_VARS or $HTTP_GET_VARS, you better stop now. Instead, you should use the superglobals - $_SERVER, $_COOKIE, $_GET, $_POST, $_FILES…
preg instead or ereg
If you're using ereg functions for regular expression tasks, then you should start using the preg functions instead. ereg will not be available in the PHP core as of version 6.
Don't initiate objects with the reference operator
If you're initiating objects using the reference operator, you should stop now. It will generate an E_STRICT error in PHP6.
$a = & new object(); // Do not do this;
$a = new object(); // Do this as of PHP6
Unofficial PHP6 Changelog
* FILE_BINARY and FILE_TEXT constants available for use with filesystem functions.
* register_globals will be gone.
* magic_quotes will also disappear.
* $HTTP_*_VARS has been removed, in favour for $_GET, $_POST, etc.
* ereg() no longer available in core PHP6.
* Initiating objects with the reference operator (& new Object()) will generate E_STRICT error.
* E_STRICT error messages are included in E_ALL errors.
* {} for string offsets no longer available.
* [] un-deprecated for accessing characters in a string.
* ASP-style tags can no longer be used.
* Better Unicode Support. (Full Unicode Support)
* var will be an alias of public, and raises E_STRICT warning.
* Support for 64 bit integers.
* With ternary operator, the "true" expression is no longer required - this can be done: $a = $s ?: 'b'; (Not clear yet exactly how this will work).
* zend.ze1_compatibility_mode removed.
* safe_mode is being removed.
* Freetype1 and GD1 support removed.
* dl() is only enabled when a SAPI layers registers it explicitly.
* Support for dynamic break levels removed.
* XMLReader and XMLWriter will be in the core distribution.
* mime_magic removed from the core.
* Fileinfo moved to the core.
* ext/soap on by default.
* foreach supports multi-dimensional arrays: foreach($a as $b => list($c, $d))
* microtime() will return as float by default.
* opcode cache included in core distribution, but turned off by default.
* flags parameter available for file_get_contents().
* before_needle parameter added to strstr() - allows strstr() to return part of haystack before occurence of the needle.
* namespace, import, and goto become reserved words.
* In PHP 6, the Fileinfo extension will replace mime_magic and it will be integrated in the core while mime_magic will be taken out of the core and changed into extension.
* In PHP 6, the exclusion of the ereg frequent expressions library that is going to become an extension.
* PHP which can be exploited by those who are practicing Denial of Service (DoS) type attacks upon a system which is affected.
What's New in PHP 5 - Database Support
PHP 5 offers some big enhancements to its ability to interact with databases. The most significant addition is the embedded SQLite database, a quick, lightweight database engine made specifically for embedded applications. This means there is no RDBMS process running on the server; SQLite reads and writes directly to files on disk. This results in significantly lower memory overhead when the database is not being used, but major performance problems arise if the system is used in a high traffic environment. SQLite is intended for small scale use, as best I can gather.
When testing it with small tables and less than one thousand rows per table, it was comparable to MySQL in executing simple joins with only one concurrent request, but performance from SQLite degraded exponentially with five or more concurrent connections coming in, which makes perfect sense. This is a good database solution for a small site that needs minimal features and expects minimal usage. It could also be useful for storing embedded configuration data in a PHP 5 application that may house its main data store in another RDBMS, and only run small queries against SQLite. SQLite is relatively standards compliant with a few major exceptions, most notably the lack of an ALTER TABLE statement.
PHP 5 also introduces support for the MySQL 4.1 client library with the introduction of the mysqli extension. The mysqli extension provides some basic objects for working with the MySQL server. The mysqli class is used as a connection object and as the ability to open and close connections as well as get context and state information from the server. The mysqli_stmt class represents a prepared statement that allows you to execute “prepare” and “execute” queries against the database. Lastly, the mysqli_result object provides a cursor based interface for reading results, providing similar functionality to the functions available in the standard MySQL extension using a MySQL resource handle. The new extension also adds support for SSL and input/output parameters.
The last notable addition in the database area is enhanced support for Firebird/InterBase, an RDBMS that offers most ANSI SQL-92 features and runs on most operating systems. The ibase extension provides most of the same functionality for Firebird/InterBase as the new mysqli extension does for MySQL but in the same manner as the old MySQL extension - that is, no objects.
What's New in PHP 5 - SPL: Exceptions and Iterators
PHP 5 comes with the Standard PHP Library (SPL), a collection of objects built to handle various tasks such as exception handling and object traversal (iteration). There are basically six groups of classes/interfaces available natively to the SPL.
1. Iterators: SPL provides built in iterators to assist in a common task - object traversal. Iterators provide a way to traverse an object’s contents without exposing the inner workings of the object to the outside world. Iterators can be built to work on any data structure and provide a standardized interface. Some of the iterator classes and interfaces available in the SPL are: Iterator, OuterIterator, RecursiveIterator, IteratorIterator, ParentIterator, SeekableIterator, NoRewindIterator, and InifiniteIterator.
Each iterator has a specific purpose and details can be found in the PHP manual.
2. Directories: Two directory classes are available in the SPL: DirectoryIterator and RecursiveDirectoryIterator. These classes allow iterator based directory traversal and eliminates the need for messy directory handles.
3. XML: There is one XML handling class in SPL, SimpleXMLIterator, which provides iteration over a simplexml object.
4. Arrays: SPL offers something that has long been in need in PHP - ArrayObject and ArrayIterator. These object provide, as you may have guessed, an array object as well as an object to traverse the contents of an array without making assumptions on the way the array is storing it's internal data.
5. Counting: The SPL interface Countable allows you to hook into the standard array function count(), meaning you can use the count() function on a user defined object and get a meaningful result by implementing the Countable interface. This is very useful for non-simple data structures.
6. Exceptions: Probably the biggest feature addition via the SPL, exceptions allow graceful error handling through try/catch blocks. The Exception class is simple to extend and the SPL provides a few standard classes of exceptions for common problems, such as LogicException, BadFunctionCallException, DomainException, OutOfRangeException, and InvalidArgumentException. Error handling has been a longtime problem in PHP and has resulted in some of the ugliest code I've ever seen, particularly using the PEAR error class. Exceptions should eliminate this sort of problem in the future.
What's New in PHP 5 - OOP: Object Enhancements
PHP 5 makes leaps and bounds in its support for objects. Aside from all the new features, Zend claims to have addressed the performance problems involved with object creation and usage in previous versions of PHP, a fact that in itself should encourage more developers to use object-based PHP. PHP 5 offers enhancements in a few key areas including object autoloading, destructors, visibility, static methods, class constants, type hinting, interfaces, cloning, reflection and several magic methods.
Autoloading is a great new feature that provides a way for developers to make sure all dependencies for a class are in place before using it. If you attempt to instantiate a class that has not yet been defined, PHP 5 will call the __autoload() function as a last attempt to load the class before failing with an error. Since most developers put one class per file, and many classes often depend on another either by way of inheritance or encapsulation, __autoload() allows you to make sure all the necessary class files have been included. While PHP 4 had constructors, PHP 5 offers a new features: destructors. Destructors are called when an object is destroyed or all references to it have been removed. Destructors are implemented in classes by use of the __destruct function. The __construct function has also been introduced and takes precedence over the old-style constructor function. The old style still works, but it is recommended that __construct is used as it takes higher priority.
One of the biggest additions to PHP's support for objects is visibility modifiers, also known as access modifiers. The var keyword has been deprecated and class variables are now to be declared as public, private, or protected. Public class variables are available to any other part of the program. Private variables are only available to that class. Protected variables are available to a class as well as its child classes, unlike private which only allows the class itself to access the variable. Methods can also be declared as public, private, or protected, and if none are declared a method is assumed to be public. Access modifiers allow PHP programmers to programmatically hide the inner workings of one object from another by preventing other objects from accessing class data directly. PHP 5 also introduces the static keyword. Static methods are called without an object instance and calls to static methods are resolved at compile time, not runtime. Static properties are accessed by the :: operator, not ->, and the special variable $this is not available in static methods.
Not only can you declares constants in C-style syntax, const constant = 'constant value';, but a class can contain it's own constants and access them internally using self::constant. This simplifies management of constants and keeps them contained within the classes they belong to, preventing code clutter and conflicts with other constants in the same application that may need the same name but a different value. PHP 5 also allows type hints in method parameter declarations. If a parameter is given a type hint and an object of the wrong type is passed to it, PHP will generate a fatal error. It would be preferable for an exception to be thrown, but type hinting does at least allow responsibility to be placed in the calling code for making sure the proper data type is passed into a function call. Type hints can be used in any function, not strictly in class methods.
PHP 5 also introduces abstract classes and interfaces, which is probably THE most significant enhancement to the language. Abstract classes and interfaces allow high level design principles to be semantically applied to PHP classes. PHP includes three special method keywords, final, abstract and virtual, to facilitate the use of inheritance and interfaces. When a method is declared as final, it cannot be overridden by a child class. When a method is declared as abstract, it must be defined in a child class. When a method is declared as virtual, it may be inherited as is or overridden by a child class. When used in combination, abstract classes and interfaces enforce high level design throughout all levels of implementation and support properly coded objects. They can be used in excess, as can anything else, but used properly these are the most powerful tools available to object oriented developers.
The last features of note are object cloning, some more magic functions and the reflection class. Object cloning allows the implementation of a magic method, __clone() to define what exactly takes place when clone is called on an object. It allows developers to implement deep copying of object data when cloning without writing messy code. A few other noteworthy magic functions are __sleep() and __wakeup(), which are used in conjunction with serialize and unserialize to ensure proper destruction and recreation of resources used within an object. Additionally, the __toString magic method allows a class to decide how to react when it is used in string context. The reflection class works as the name implies; it allows developers to programmatically reverse-engineer classes, interfaces, functions and extensions. Reflection is a powerful tool in developing custom application frameworks.
Conclusion
Overall, PHP 5 offers dramatic improvements over PHP 4 in a lot of areas. These improvements are, by and large, geared toward advanced PHP developers. With the exception of the SimpleXML extension, most of the new functionality will probably have no appeal to the largest segment of the PHP programming population - that is, developers who look at PHP as a simple scripting language and use it to accomplish one task at a time. For PHP application developers though, I see PHP 5 quickly becoming the de facto standard. Start putting pressure on your hosts now to upgrade, because PHP 5 was definitely worth the wait.
Snippets
class Foo
{
function __construct()
{
}
function Foo()
{
self::__construct();
}
}
?>
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home