Basic knowledge: Differences between PHP4 and PHP5

Source: Internet
Author: User
Tags abstract constructor copy error handling exception handling getmessage inheritance variables

The objects in the PHP5 have been systematically and comprehensively tuned, and may now look somewhat similar to Java. This section focuses on the new object patterns in PHP5, with some simpler examples to illustrate. Let this section be a new starting point for your PHP5 journey. :)

* Constructors and destructors
* References to Objects
* Cloning of objects
* Private, public, and protected mode in the object
* Interface (interfaces)
* Abstract class
* __call
* __set and __get
* Static member


Constructors and destructors

In PHP4, when a function has the same name as an object, the function becomes the constructor of the object, and there is no concept of destructors in the PHP4.
In PHP5, constructors are uniformly named __construct, and the concept of destructors is introduced, which is uniformly named __destruct.

Example one: constructors and destructors

class Foo {
var $x;
function __construct ($x) {
$this->x = $x;
}
function display () {
Print ($this->x);
}
function __destruct () {
Print ("Bye Bye");
}
}
$o 1 = new Foo (4);
$o 1->display ();
?>
In the above example, when you terminate the call to the Foo class, its destructor will be invoked, and the "Bye Bye" will be printed in the example above.


References to Objects

As we all know, in the PHP4, passing a variable to a function or method, which actually makes a copy of the variable, means that you pass a copy of the variable to the function or method, unless you use the reference symbol "&" to declare a reference, not a copy. In PHP5, an object is always in the form of a reference, and the assignment operation in the object is also a reference operation.

Example two: A reference to an object


class Foo {
var $x;
function SetX ($x) {
$this->x = $x;
}
function GetX () {
return $this->x;
}
}
$o 1 = new Foo;
$o 1->setx (4);
$o 2 = $o 1;
$o 1->setx (5);
if ($o 1->getx () = = $o 2->getx ()) print ("Oh my god!");
?>

Cloning of objects

What if I want to get a copy of an object that is always invoked as a reference, as described above? PHP5 provides a new feature, that is, the cloning of objects, the syntax is __clone.

Example three: Cloning of objects
class Foo {
var $x;
function SetX ($x) {
$this->x = $x;
}
function GetX () {
return $this->x;
}
}
$o 1 = new Foo;
$o 1->setx (4);
$o 2 = $o 1->__clone ();
$o 1->setx (5); if ($o 1->getx ()!= $o 2->getx ()) print ("Copies are independant");
?>
The method of object cloning exists in many other application languages, so you don't have to worry about its stability. :)


Private, public, and protected mode in the object

In PHP4, all the methods and variables of an object are public, which means that you can manipulate any one of these variables and methods outside of an object. PHP5 introduced three new patterns for controlling this access, which are public, protected (Protected), and proprietary (private).

Common mode (public): Allows manipulation control outside the object.
Private mode: Only the methods within this object are allowed to manipulate it.
Protected Mode (Protected): Allows this object and its parent object to manipulate it.

Example four: Private, public, and protected mode in the object

class Foo {
Private $x;
Public Function Public_foo () {
Print ("I ' m public");
}
protected function Protected_foo () {
$this->private_foo (); Ok because we are in the same class we can call private methods
Print ("I ' m protected");
}
Private Function Private_foo () {
$this->x = 3;
Print ("I ' m private");
}
}
Class Foo2 extends Foo {
Public Function display () {
$this->protected_foo ();
$this->public_foo ();
$this->private_foo (); invalid! The function is private in the base class
}
} $x = new Foo ();
$x->public_foo ();
$x->protected_foo (); Invalid cannot call protected methods outside the class and derived classes
$x->private_foo (); Invalid private methods can only used inside the class $x 2 = new Foo2 ();
$x 2->display ();
?>
Tip: Variables in an object are always in the private form, and directly manipulating variables in an object is not a good object-oriented programming habit, and a better approach is to give the variable you want to an object.


Interface (interfaces)

As we all know, objects in PHP4 support inheritance, and to make an object a derived class of another object, you need to use code similar to "class Foo extends parent" to control it. In PHP4 and PHP5, an object can only be inherited once, and multiple inheritance is not supported. However, a new noun was produced in the PHP5: interface, an interface is a special object that does not deal with code specifically, it only defines the name and parameters of some methods, then the object can easily use the ' implement ' keyword to integrate the required interfaces, and then add the specific execution code.

Example five: interface

Interface Displayable {
function display ();
}
interface Printable {
function Doprint ();
}

Class Foo implements displayable,printable {
function display () {
Code
function Doprint () {
Code
}
}
?>
This helps to improve the readability and popularity of the code, and as you can see from the example above, Object Foo contains the displayable and printable two interfaces, and we can clearly see that object Foo must have a display () method and a print () method, you simply need to understand the interface, and you can easily manipulate the object without having to worry about how the object's interior works.

Abstract class

Abstract classes cannot be instantiated.
Abstract classes, like other classes, allow you to define variables and methods.
An abstract class can also define an abstract method, and the method of an abstract class will not be executed, but it will be possible to execute it in its derived class.

Example VI: abstract class

Abstract class Foo {
protected $x;
Abstract function display ();
function SetX ($x) {
$this->x = $x;
}
}
Class Foo2 extends Foo {
function display () {
Code
}
}
?>

__call

The PHP5 object adds a dedicated method __call (), which is used to monitor other methods in an object. If you try to call a method that does not exist in an object, the __call method will be invoked automatically.

Example Seven: __call

class Foo {
function __call ($name, $arguments) {
Print ("Did You Call me?") I ' m $name! );
}
} $x = new Foo ();
$x->dostuff ();
$x->fancy_stuff ();
?>
This particular method can be used to implement the "overload (overloading)" Action so that you can check your parameters and pass the arguments by calling a private method.

Example eight: Using __call to implement "overload" action

Class Magic {
function __call ($name, $arguments) {
if ($name = = ' Foo ') {
if (Is_int ($arguments [0])) $this->foo_for_int ($arguments [0]);
if (is_string ($arguments [0])) $this->foo_for_string ($arguments [0]);
}
Private Function Foo_for_int ($x) {
Print ("Oh an int!" );
Private Function foo_for_string ($x) {
Print ("Oh a string!" );
}
} $x = new Magic ();
$x->foo (3);
$x->foo ("3");
?>

__set and __get

This is a great way to __set and __get methods that can be used to capture variables and methods that do not exist in an object.

Example nine: __set and __get

class Foo {
function __set ($name, $val) {
Print ("Hello, tried to put $val in $name");
}
function __get ($name) {
Print ("Hey asked for $name");
}
}
$x = new Foo ();
$x->bar = 3;
Print ($x->winky_winky);
?>

Type indication

In PHP5, you can indicate in the object's method that its arguments must be an instance of another object.

Example Ten: Type indication

class Foo {
Code ...
}
Class Bar {
Public Function Process_a_foo (foo $foo) {
Some Code
}
}
$b = new Bar ();
$f = new Foo ();
$b->process_a_foo ($f);
?>
As you can see, we can explicitly indicate the name of an object before the argument, and PHP5 will recognize that this parameter will be an object instance.


Static members

Static members and static methods are referred to as Object methods (class methods) and object variables (class variables) in the terminology of object programming.
The object method is allowed to be invoked before an object is instantiated. Similarly, object variables can be manipulated independently of an object before it is instantiated (without the need for an object's method to control it).

Example 11: Object methods and Object variables

Class Calculator {
static public $pi = 3.14151692;
static public function Add ($x, $y) {
return $x + $y;
}
}
$s = calculator:: $pi;
$result = Calculator::add (3,7);
Print ("$result");
?>

Exception handling

Exception handling is an ideal way to deal with Bugs in Java and C + +, and we are delighted to see that PHP5 has been added to this application. You can try using "try" and "catch" to control the error.

Example 12: Exception handling

class Foo {
function Divide ($x, $y) {
if ($y ==0) throw new Exception ("Cannot divide by zero");
return $x/$y;
}
}
$x = new Foo ();
try {
$x->divide (3,0);
catch (Exception $e) {
echo $e->getmessage ();
echo "n
n ";
Some catastrophic measure here
}
?>
In the example above, we used "try" to execute the statement in curly braces. When there is an error, the code takes the error to the catch clause, and in the catch clause, you need to indicate that you want to give the error to an object, which makes the structure of the code look clearer. Because now we can give all the wrong information to an object to handle.


Custom error Handling

You can easily control the unexpected in your program with custom handling of the wrong code. You just need to derive your own error control class from the exception class, and in your own error control class you need to have a constructor and a GetMessage method, and here's an example.

Example 13: Custom error handling

Class Weirdproblem extends Exception {
Private $data;
function Weirdproblem ($data) {
Parent::exception ();
$this->data = $data;
}
function GetMessage () {
Return $this->data. "caused a weird exception!";
}
}
?>
Now we can use "throw new Weirdproblem ($foo)" to throw an error handle, if the error occurs in the code block of "Try", PHP5 automatically hands the error to the "Catch" section.


Name space

Namespaces are useful for grouping or grouping groups of classes. It can be combined with some related classes or functions to make it easier to call later.

Example 14: namespace

Namespace Math {
Class Complex {
... code ...
function __construct () {
Print ("Hey");
}
}
} $m = new Math::complex ();
?>
Notice where you need to use namespaces, and in practice, you might need to declare two or more names of objects to do different things, so you can put them in different namespaces (but the interfaces are the same).



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.