Basic knowledge: differences between php4 and php5

Source: Internet
Author: User
Objects in PHP5 have been adjusted in a more systematic and comprehensive manner. the current situation may look a little similar to Java. This section focuses on the new object mode in PHP5 and illustrates some simple examples. Let this section be a new starting point for your PHP5 journey. :)

Objects in PHP5 have been adjusted in a more systematic and comprehensive manner. the current situation may look a little similar to Java. This section focuses on the new object mode in PHP5 and illustrates some simple examples. Let this section be a new starting point for your PHP5 journey. :)

* Structure functions and Destructor
* Object reference
* Object cloning
* Private, public, and protected modes in the object
* Interface (Inte *** ces)
* Abstract class
* _ Call
* _ Set and _ get
* Static members


Structure functions and Destructor

In PHP4, when a function has the same name as an object, this function will become a structure function of the object, and there is no destructor concept in PHP4.
In PHP5, the constructor is named _ construct at the same time, and the constructor concept is introduced. It is named _ destruct at the same time.

Example 1: structure functions and Destructor

Class foo {
Var $ x;
Function _ construct ($ x ){
$ This-> x = $ x;
}
Function display (){
Print ($ this-> x );
}
Function _ destruct (){
Print ('Bye Bye ');
}
}
$ O1 = new foo (4 );
$ O1-> display ();
?>
In the above example, when you terminate the call to the foo class, the destructor will be called, and "bye" will be output in the above example ".


Object reference

As we all know, in PHP4, when a variable is passed to a function or method, the variable is actually copied once, which means that you pass a copy of the variable to the function or method, unless you apply the reference symbol "&" to declare that you want to make a reference, not a Copy. In PHP5, the object is always referenced, and the value assignment control in the object is also a reference control.

Example 2: Object reference


Class foo {
Var $ x;
Function setX ($ x ){
$ This-> x = $ x;
}
Function getX (){
Return $ this-> x;
}
}
$ O1 = new foo;
$ O1-> setX (4 );
$ O2 = $ o1;
$ O1-> setX (5 );
If ($ o1-> getX () = $ o2-> getX () print ('Oh my god! ');
?>

Object cloning

As mentioned above, when an object is always called as a reference, what should I do if I want a copy of the object? PHP5 provides a new function, that is, object cloning. The syntax is _ clone.

Example 3: Object cloning
Class foo {
Var $ x;
Function setX ($ x ){
$ This-> x = $ x;
}
Function getX (){
Return $ this-> x;
}
}
$ O1 = new foo;
$ O1-> setX (4 );
$ O2 = $ o1->__ clone ();
$ O1-> setX (5); if ($ o1-> getX ()! = $ O2-> getX () print ('copies are independant ');
?>
Object cloning methods exist in many other languages, so you don't have to worry about its stability. :)


Private, public, and protection modes of objects

In PHP4, all methods and variables of an object are public, which means that you can hold any variable and method outside an object. PHP5 introduces three new access control modes: Public, Protected, and Private ).

Public mode: The Public mode is used to control the external part of the object.
Private Mode: only the methods in this object are allowed to control the method.
Protected Mode (Protected): allows the current object and its parent object to control it.

Example 4: private, public, and protected modes of objects

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 be used inside the class $ x2 = new foo2 ();
$ X2-> display ();
?>
Tip: variables in an object always exist in a private situation. directly controlling variables in an object is not a good object-oriented programming habit, A better way is to give the variable you want to an object to process it.


Interface (Inte **** ces)

As we all know, objects in PHP4 support persistence. to make an object a derived class of another object, you need to apply code similar to "class foo extends parent. In PHP4 and PHP5, an object can only last once, and multiple persistence is not supported. However, a new term is generated in PHP5: interface, which is a special object without specific code processing. it only defines the names and parameters of some methods, after that, the object can easily apply the 'enablement' keyword to integrate the required interfaces, and then participate in specific code fulfillment.

Example 5: Interface

Inte *** ce displayable {
Function display ();
}
Inte *** ce printable {
Function doprint ();
}

Class foo implements displayable, printable {
Function display (){
// Code
} Function doprint (){
// Code
}
}
?>
This is of great help to improve the readability and popularity of the code. from the example above, we can see that the object foo contains the displayable and printable interfaces. then we can understand that, the object foo must have a display () method and a print () method. you only need to understand the Interface section, you can easily control the object without worrying about how the object works.

Abstract class

Abstract classes cannot be instantiated.
Abstract classes, like other classes, promise to define variables and methods.
An abstract class can also define an abstract method. an abstract class method is not executed, but may be executed in its derived class.

Example 6: abstract class

Abstract class foo {
Protected $ x;
Abstract function display ();

Function setX ($ x ){
$ This-> x = $ x;
}
}
Class foo2 extends foo {
Function display (){
// Code
}
}
?>


_ Call

A special _ call () method is added to the PHP5 object. this method is used to supervise other methods in an object. If you try to call a method that does not exist in an object, the __call method will be called proactively.

Example 7: __call

Class foo {
Function _ call ($ name, $ arguments ){
Print ('Did you call me? I'm $ name! ');
}
} $ X = new foo ();
$ X-> doStuff ();
$ X-> fancy_stuff ();
?>
This special method can be used to implement the "overload" action, so that you can check your parameters and pass parameters by calling a private method.

Example 8: use _ call to achieve "overload"

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 method. the __set and _ get methods can be used to capture variables and methods that do not exist in an object.

Example 9: _ set and _ get

Class foo {
Function _ set ($ name, $ val ){
Print ('Hello, you tried to put $ val in $ name ');
}
Function _ get ($ name ){
Print ('hey you asked for $ name ');
}
}
$ X = new foo ();
$ X-> bar = 3;
Print ($ x-> winky_winky );
?>

Type instigation

In PHP5, you can specify in the object method that the parameter must be an instance of another object.

Example 10: type instigation

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 );
?>
We can see that we can explicitly specify the name of an object before the parameter, PHP5 will identify this parameter as an object instance.


Static Member

Static members and static methods are called "class methods" and "class variables" in terms of face object programming )".
The "object method" is called before an object is instantiated. Similarly, "object variables" can be independently held before an object is instantiated (an object method is not needed ).

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 a widely recognized fantasy method for handling program errors. it is a concept in Java and C. We are delighted to see that PHP5 has taken part in this use. You can apply "try" and "catch" to handle program errors.

Example 12: Exception handling

Class foo {
Function divide ($ x, $ y ){
If ($ y = 0) throw new Exception ('cannot divide by 0 ');
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 above example, we applied "try" to execute the statements in curly brackets. When an error is generated, the code will hand over the error to the "catch" clause for processing, in the "catch" clause, you need to specify that an error should be handed over to an object for processing. this can make the code structure more clear, now we can give all the error information to an object for processing.


Custom error handling

You can easily use custom code to handle errors to control exceptions in your program. You only need to generate an error control class from the exception class. in your own error control class, you need a structure function and a getMessage method. The following is 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 apply "throw new WeirdProblem ($ foo)" to throw an error handle. if the error is generated in the "try" code block, PHP5 will take the initiative to hand over the error to the "catch" part for processing.


Namespace

Namespaces are useful for grouping classes or function groups. It can combine some coherent classes or functions to facilitate future calls.

Example 14: namespace

Namespace Math {
Class Complex {
//... Code...
Function _ construct (){
Print ('hes ');
}
}
} $ M = new Math: Complex ();
?>
Pay attention to the situations in which you need to apply namespaces. in actual applications, you may need to declare two or more objects with the same name for different purposes, then you can differentiate them into different namespaces (but the interfaces must be 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.