The objects in PHP5 have been adjusted more systematically and comprehensively, and their current appearance may look somewhat similar to Java. This section focuses on the new object mode in PHP5 and gives some simpler examples to illustrate. Let this section be a new starting point for your PHP5 journey. :)
* Constructor and destructor
* Object reference
*Clone of object
* Private, public and protected modes in objects
* Interfaces
* Abstract class
* __call
* __set and __get
* Static members
Constructor and destructor
In PHP4, when a function has the same name as an object, this function will become the constructor of the object, and there is no concept of destructor in PHP4.
In PHP5, the constructor is uniformly named __construct, and the concept of destructor is introduced, which is uniformly named __destruct.
Example 1: Constructor 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 class foo, its destructor will be called, and "bye bye" will be output in the above example.
object references
, in PHP4, passing a variable to a function or method actually makes a copy of the variable, which means that what you pass to the function or method is a copy of the variable, unless you use a reference. The symbol "&" is used to declare that a reference is to be made, not a copy. In PHP5, objects always exist in the form of references, and assignment operations in objects are also reference operations.
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!");
?>
Clone of Object
As mentioned above, when an object is always called in the form of a reference, what should I do if I want to get a copy of the object? PHP5 provides a new function, which is object cloning, and the syntax is __clone.
Example 3: Cloning of objects
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 application languages, so you don't have to worry about its stability. :)
Private, public and protected modes in objects
In PHP4, all methods and variables of an object are public, which means that you can operate any of the variables and methods outside an object. PHP5 introduces three new modes for controlling this access permission: Public, Protected, and Private.
Public mode (Public): allows operation control outside the object.
Private mode (Private): Only methods within this object are allowed to operate and control it.
Protected mode (Protected): Allows this object and its parent object to operate and control it.
Example 4: Private, public and protected modes in 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 objects always exist in private form. Directly operating variables in an object is not a good object-oriented programming habit. A better way is to hand over the variables you want to an object's method for processing. .
Interfaces
As we all know, objects in PHP4 support inheritance. 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 term was born in PHP5: interface. An interface is a special object without specific processing code. It only defines the names and parameters of some methods. After that, the object can be conveniently used with the 'implement' keyword. The required interfaces are integrated, and then the specific execution code is added.
Example 5: Interface
interface displayable {
function display();
}
interface printable {
function doprint();
}
class foo implements displayable,printable {
function display() {
// code
} function doprint() {
// code
}
}
?>
This is very helpful to improve the readability and popularity of the code. From the above example, we can see that the object foo contains two interfaces, displayable and printable. At this time, we can clearly know that the object foo must have A display() method and a print() method, you only need to understand the interface part, you can easily operate the object without having to care about how the object works internally.
Abstract classes
Abstract classes cannot be instantiated.
Abstract classes, like other classes, allow variables and methods to be defined.
An abstract class can also define an abstract method. The method of the abstract class will not be executed, but it 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
PHP5 objects have a new dedicated method __call(), which is used to monitor other methods in an object. If you try to call a method that does not exist on the object, the __call method will be called automatically.
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 "overloading" actions, so that you can check your parameters and pass them by calling a private method.
Example 8: 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 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 indication
In PHP5, you can specify in an object's method that its parameter must be an instance of another object.
Example 10: 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 can be seen, we can explicitly specify the name of an object before the parameter, and PHP5 will recognize that the parameter will be an object instance.
Static members
Static members and static methods are called "object methods (class methods)" and "object variables (class variables)" in object-oriented programming terminology.
"Object methods" are allowed to be called before an object is instantiated. Similarly, "object variables" can be controlled independently before an object is instantiated (without using an object's methods 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 recognized as an ideal method for handling program errors. This concept is available in Java and C++. We are pleased to see that this application has been added to PHP5. You can try using "try" and "catch" to control program errors.
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 measures here
}
?>
In the above example, we used "try" to execute the statement in curly brackets. When an error occurs, the code will hand over the error to the "catch" clause for processing. In the "catch" clause, you need to specify Handling errors to an object can make the code structure look clearer, because now we can hand all error information to an object for handling.
Custom Error Handling
You can easily control accidents in your program with custom error handling code. You just need to derive your own error control class from the exception class. In your own error control class, you need to have a constructor 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 use "throw new WeirdProblem($foo)" to throw an error handler. If the error occurs in the "try" code block, PHP5 will automatically hand the error to the "catch" part for processing.
Namespaces
Namespaces are useful for grouping of classes or grouping of functions. It can group some related classes or functions together for easy calling later.
Example 14: Namespace
namespace Math {
class Complex {
//...code...
function __construct() {
print("hey");
}
}
} $m = new Math::Complex();
?>
Pay attention to the circumstances under which you need to use namespaces. In practical applications, you may need to declare two or more objects with the same name to do different things, then you can put them in different namespaces. (but the interface must be the same).