H5 PHP5 new Features: More object-oriented PHP

Source: Internet
Author: User
Tags gtk rewind throwable
The kernel of the PHP Processing Object section has been completely re-developed, providing more functionality while also improving performance. In previous versions of PHP, objects were handled the same way as basic types (numbers, strings). The flaw in this approach is that when an object is assigned to a variable, or when an object is passed through a parameter, the object is completely copied. In the new version, the above operation will pass the reference (which can be interpreted as an identifier of the object), not a value.
Many PHP programmers may not even be aware of the way old objects are handled. In fact, most PHP applications can run well. Or just need a little change.
Private and protected members
PHP5 introduces the concept of private and protected member variables. We can use it to define the visibility of class members.
Example
Protected members can be accessed by subclasses, while private members are accessible only to the class itself.
Class 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 ();
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 methods and protected methods
PHP5 also introduces the concept of private methods and protected methods.
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 ();
?>
Previous old code that did not use the class, the code without the access modifier (public, protected, private) can run without modification.
Abstract classes and abstract methods
PHP5 also introduces the concepts of abstract classes and abstract methods. The abstract method simply declares that the signature of the method does not provide its implementation. Classes that contain abstract methods must 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. Previous old code that did not use abstract classes could run without modification.
Interface
PHP5 introduces an interface. A class can implement multiple interfaces.
Example:
Interface Throwable {
Public function getMessage ();
}
Class MyException implements Throwable {
Public Function GetMessage () {
// ...
}
}
?>
Previous old code that does not use interfaces can be run without modification

Type hints for classes
PHP5 is still a weak type, but when defining a function parameter, you can use the class's type hint to declare the expected incoming object type
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);
?>
Like other strongly typed languages, the type hint of the PHP5 class is checked during run time, not during compilation. That
function foo (ClassName $object) {
// ...
}
?>
And the following code is the same:
function foo ($object) {
if (! ( $object instanceof ClassName)) {
Die ("Argument 1 must is an instance of ClassName");
}
}
?>
This syntax applies only to classes, not to built-in types.
Final
PHP 5 introduces the final keyword to declare the final member and final method. Final members and final methods cannot be overridden by a quilt class.
Example
Class Foo {
Final function bar () {
// ...
}
}
?>
Further, you can declare the class as final. Declaring a class as final prevents the class from being inherited. The methods inside the final class are final by default, without having to declare them again.
Example
Final class Foo {
Class definition
}
The next line is impossible
Class Bork extends Foo {}
?>
property cannot be defined as final.
Previous old code that did not use final can be run without modification.
Object cloning
PHP4 does not provide a mechanism for the user to define the copy process of the copy constructor control object themselves. PHP4 makes a binary copy, so it replicates all the properties of the object very precisely.
Copying all the properties of an object accurately may not be what we always wanted. One example is a good illustration of the fact that we really need to copy a constructor: A GTK Window object, for example. A holds all the resources it needs. When copying this GTK window to object B, we would prefer B to hold a new resource object. Another example: Object A contains an object, C, when you copy object A to object C. We might prefer that object B contains a copy of the new object C, not a reference to object C. (Translator Note: This is a shallow clone and a deep clone.) )
The copy of the object is reached by the keyword clone (clone calls the __clone () method of the cloned object). The __clone method of the object cannot be called directly.
$copy _of_object = Clone $object;
?>
When developer creates a copy of the object, PHP5 checks to see if the __clone () method exists. If it does not exist, it will call the default __clone () method, copying all properties of the object. If the __clone () method is already defined, then the _clone () method is responsible for setting the properties of the new object. For convenience, the engine copies all properties by default. So in the __clone () method, you just need to overwrite the attributes that need to be changed. As follows:
Example
Class Mycloneable {
static $id = 0;
function mycloneable () {
$this->id = self:: $id + +;
}
function __clone () {
$this->address = "New York";
$this->id = self:: $id + +;
}
}
$obj = new Mycloneable ();
$obj->name = "Hello";
$obj->address = "Tel-aviv";
Print $obj->id. "\ n";
$obj _cloned = Clone $obj;
Print $obj _cloned->id. "\ n";
Print $obj _cloned->name. "\ n";
Print $obj _cloned->address. "\ n";
?>
Unified constructors
PHP5 allows developers to declare how a class is constructed. A class that has a constructor method calls this method every time a new object is created, so the constructor works well for the initialization of the object before it is used.
In Php4, the name of the constructed method is the same as the name of the class. It is quite common to consider that the construction method of the parent class is called from the subclass construction method, and the change of the parent class from the removal of the class from an inheritance system often leads to the need to change the construction method of the class, which is obviously php4.
PHP5 introduces a standard method for declaring a build function: __construct (). The following:
Example
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 ();
?>
To maintain backwards compatibility, if PHP5 cannot find __construct (), it will look for old-fashioned construction methods, that is, the same name as the class. Simply put, there is a compatibility problem only when the old code contains a __construct () method.
destructor method
For object-oriented programming, it is a useful function to define a destructor method. The destructor method can be used to record debugging information, close the database connection, and so on some cleanup finishing work. There is no destructor in Php4, although PHP4 already supports the ability to register a function to be called at the end of a request.
The concept of PHP5 introduced by the destructor is consistent with other object-oriented languages such as Java. When the last reference to the object is destroyed, the destructor is called and the memory is freed when the call is complete. Note: The destructor method does not accept any parameters.
Example
Class Mydestructableclass {
function __construct () {
Print "in constructor\n";
$this->name = "Mydestructableclass";
}
function __destruct () {
Print "destroying". $this->name. "\ n";
}
}
$obj = new Mydestructableclass ();
?>
As with the build method, the Destructor method of the parent class is not implicitly called. Subclasses can call it explicitly in their own destructor by calling Parent::__destruct ().
Constants
PHP5 introduces a class-level constant.
Class Foo {
CONST CONSTANT = "constant";
}
echo "foo::constant =". Foo::constant. "\ n";
?>
The old code that does not use const still runs normally.
Exceptions
PHP4 no exception control. PHP5 introduces exception control patterns similar to other languages (Java). It should be noted that the PHP5 supports catching all exceptions, but the finally clause is not supported.
Inside the catch statement block, you can re-throw the exception. There can also be multiple catch statements, in which case the caught exception is compared from top to bottom and the catch statement compares the exception, and the first type-matched catch statement is executed. If the search has not yet found a matching catch clause, look for the next Try/catch statement. The last exception that cannot be captured is displayed. If the exception is caught, then the program starts execution below the catch statement block.
Example
Class MyException {
function __construct ($exception) {
$this->exception = $exception;
}
function Display () {
Print "MyException: $this->exception\n";
}
}
Class Myexceptionfoo extends MyException {
function __construct ($exception) {
$this->exception = $exception;
}
function Display () {
Print "MyException: $this->exception\n";
}
}
try {
throw new Myexceptionfoo (' Hello ');
}
catch (MyException $exception) {
$exception->display ();
}
catch (Exception $exception) {
Echo $exception;
}
?>
The above example shows that you can define an exception class that does not inherit from exception, but it is best to inherit from exception and define your own exceptions. This is because the built-in exception class can collect a lot of useful information, and the exception class that does not inherit it is not available. The following PHP code mimics the system's built-in exception class. Comments are appended to each property. Each property has a getter, and because these getter methods are often called internally by the system, these methods are marked final.
Example
Class Exception {
function __construct (string $message =null, int code=0) {
if (Func_num_args ()) {
$this->message = $message;
}
$this->code = $code;
$this->file = __file__; of throw clause
$this->line = __line__; of throw clause
$this->trace = Debug_backtrace ();
$this->string = StringFormat ($this);
}
protected $message = ' Unknown exception '; Exception message
protected $code = 0; User defined exception code
protected $file; SOURCE filename of exception
protected $line; Source line of exception
Private $trace; BackTrace of exception
Private $string; Internal only!!
Final function getMessage () {
return $this->message;
}
Final function GetCode () {
return $this->code;
}
Final function GetFile () {
return $this->file;
}
Final function Gettrace () {
return $this->trace;
}
Final function gettraceasstring () {
Return Self::traceformat ($this);
}
function _tostring () {
return $this->string;
}
Static Private Function StringFormat (Exception $exception) {
... a function not available in PHP scripts
That returns all relevant information as a string
}
Static Private Function Traceformat (Exception $exception) {
... a function not available in PHP scripts
That returns the BackTrace as a string
}
}
?>
If we define an exception class that inherits from the exception base class
No compatibility issues. The old code is not affected by this feature.
dereferencing objects returned from functions
The object returned by the function cannot be referenced again in PHP4 to further call methods that return the object, while PHP5 is possible.
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 new Square ();
}
}
Shapefactorymethod ("Circle")->draw ();
Shapefactorymethod ("Square")->draw ();
?>
Static member variables can be initialized.
Example
class Foo {
static $my _static = 5;
Public $my _prop = ' bla ';
}
Print foo:: $my _static;
$obj = new Foo;
Print $obj->my_prop;
?>
Static methods
PHP 5 introduces a static method that can call a static method without instantiating the class.
Example
Class Foo {
public static function Astaticmethod () {
// ...
}
}
Foo::astaticmethod ();
?>
Pseudo-variable $this cannot be used in static method methods.
instanceof
PHP5 introduces the instanceof keyword, which allows it to be used to test whether an object is an instance of a class, an instance of a derived class, or implements an interface
Example
Class BaseClass {}
$a = new BaseClass;
if ($a instanceof BaseClass) {
echo "Hello World";
}
?>
Static function variables
Static variables are now processed during the compilation phase. So programmers can assign values to static variables by reference. This can improve performance, but it is not possible to use an indirect reference to a static variable.
Function arguments passed by reference can now also set default values.
Example
Function my_function (& $var = null) {
if ($var = = = null) {
Die (' $var needs to has a value ');
}
}
?>
__autoload ()
The __autoload () intercept function is called automatically when an undeclared class is initialized. The name of the class is automatically passed to the __autoload () function. and __autoload () has only such a single parameter.
Example
function __autoload ($className) {
Include_once $className. ". PHP";
}
$object = new ClassName;
?>
Overloaded methods for calling and property access
Both method call and property access can be overloaded by __call, __get (), and __set () methods.
Example: __get () and __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: $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 ()
Class Caller {
Private $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);
?>
Iteration
Iterations are overloaded when objects are used with foreach. The default behavior is to iterate over all properties of the class.
Example
Class Foo {
public $x = 1;
Public $y = 2;
}
$obj = new Foo;
foreach ($obj as $prp _name = $prop _value) {
Using the property
}
?>
All objects of a class can be iterated through, if the class implements an empty interface: traversable. In other words, a class that implements the Traversable interface can be used with foreach.
Interfaces Iteratoraggregate and iterator allow the specified class's objects to iterate in code. The Iteratoraggregate interface has a method: Getiterator () must return an array
Example
Class Objectiterator implements Iterator {
Private $obj;
Private $num;
function __construct ($obj) {
$this->obj = $obj;
}
Function Rewind () {
$this->num = 0;
}
function valid () {
return $this->num < $this->obj->max;
}
Function key () {
return $this->num;
}
function current () {
Switch ($this->num) {
Case 0:return "1st";
Case 1:return "2nd";
Case 2:return "3rd";
Default:return $this->num. " TH ";
}
}
function Next () {
$this->num++;
}
}
Class Object implements Iteratoraggregate {
Public $max = 3;
function Getiterator () {
return new Objectiterator ($this);
}
}
$obj = new Object;
This foreach ...
foreach ($obj as $key = = $val) {
echo "$key = $val \ n";
}
Matches the following 7 lines with the for directive.
$it = $obj->getiterator ();
For ($it->rewind (); $it->hasmore (); $it->next) {
$key = $it->current ();
$val = $it->key ();
echo "$key = $val \ n";
}
Unset ($it);
?>
The new __tostring method
You can control the conversion of an object to a string by overriding the __tostring method.
Example
Class Foo {
function __tostring () {
Return "what ever";
}
}
$obj = new Foo;
Echo $obj; Call __tostring ()
?>
Reflection API
PHP5 introduces a full set of reflection APIs to support reverse engineering of classes, interfaces, functions, and methods.
It also provides an API to extract the comment document from the program. For more information on the reflection API, refer here: http://sitten-polizei.de/php/reflection_api/docs/language.reflection.html
Example
Class Foo {
Public $prop;
function Func ($name) {
echo "Hello $name";
}
}
Reflection_class::export (' Foo ');
Reflection_object::export (new Foo);
Reflection_method::export (' Foo ', ' func ');
Reflection_property::export (' Foo ', ' prop ');
Reflection_extension::export (' standard ');
?>
New memory management mechanism
PHP5 has a new memory management mechanism that allows it to run more efficiently in multi-threaded environments. No mutex lock/unlock is used when allocating and freeing memory

The above describes the new features of H5 PHP5: More object-oriented PHP, including the H5 aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • Related Article

    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.