Deciphering Magic Methods in PHP
PHP provides a number of ‘magic’ methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method’s use.Before We Begin
In order to fully understand magic methods, it’s helpful to see them in action. So let’s start with a base set of very 易做图 classes. Here we define two classes: Device and Battery.
view plaincopy to clipboardprint?
<?php
class Device {
public $name; // the name of the device
public $battery; // holds a Battery object
public $data = array(); // stores misc. data in an array
public $connection; // holds some connection resource
protected function connect() {
// connect to some external network
$this->connection = 'resource';
echo $this->name . ' connected' . PHP_EOL;
}
protected function disconnect() {
// safely disconnect from network
$this->connection = null;
echo $this->name . ' disconnected' . PHP_EOL;
}
}
class Battery {
private $charge = 0;
public function setCharge($charge) {
$charge = (int)$charge;
if($charge < 0) {
$charge = 0;
}
elseif($charge > 100) {
$charge = 100;
}
$this->charge = $charge;
}
}
?>
If words like “method” and “property” sound alien to you, you might want to read up on this first.
Device objects will hold a name, a Battery object, an array of data, and a handle to some external resource. They also have methods for connecting and disconnecting the external resource. Battery objects simply store a charge in a private property and have a method to set the charge.
This tutorial assumes you have a basic understanding of object oriented programming. If words like “method” and “property” sound alien to you, you might want to read up on that first.
These classes are pretty useless, but they make a good example for each of the magic methods. So now that we have our 易做图 classes created, we can try out the magic methods.
Constructors & Destructors
Constructors and destructors are called when an object is created and destroyed, respectively. An object is “destroyed” when there are no more references to it, either because the variable holding it was unset/reassigned or the script ended execution.
__construct()
The __construct() method is by far the most commonly used magic method. This is where you do any initialization you need when an object is created. You can define any number of arguments here, which will be passed when creating objects. Any return value will be passed through the new keyword. Any exceptions thrown in the constructor will halt object creation.
view plaincopy to clipboardprint?
class Device {
//...
public function __construct(Battery $battery, $name) {
// $battery can only be a valid Battery object
$this->battery = $battery;
$this->name = $name;
// connect to the network
$this->connect();
}
//...
}
Declaring the constructor method ‘private’ prevents external code from directly creating an object.
Here we have declared a constructor that accepts two arguments, a Battery and a name. The constructor assigns each of the properties that the objects requires to function and runs the connect() method. The constructor allows you to ensure that an object has all the required pieces before it can exist.
Tip: Declaring the constructor method ‘private’ prevents external code from directly creating an object. This is handy for creating singleton classes that restrict the number of objects that can exist.
With the above constructor in place, here is how you create a Device called ‘iMagic’:
view plaincopy to clipboardprint?
$device = new Device(new Battery(), 'iMagic');
// iMagic connected
echo $device->name;
// iMagic
As you can see, arguments passed to the class are actually being passed to the constructor method. You can also tell that the connect method was called and the $name property was populated.
Let’s say we forget to pass a name. Here’s what happens:
view plaincopy to clipboardprint?
$device = new Device(new Battery());
// Result: PHP Warning: Missing argument 2 for Device::__construct()
__destruct()
As the name implies, the __destruct() method is called when the object is destroyed. It accepts no arguments and is commonly used to perform any cleanup operations such as closing a database connection. In our case, we’ll use it to disconnect from the network.
view plaincopy to clipboardprint?
class Device {
//...
public function __destruct() {
// disconnect from the network
$this->disconnect();
echo $this->name . ' was destroyed' . PHP_EOL;
}
//...
}
With the above destructor in place, here is what happens when a Device object is destroyed:
view plaincopy to clipboardprint?
$device = new Device(new Battery(), 'iMagic');
// iMagic connected
unset($device);
// iMagic disconnected
// iMagic was destroyed
Here, we’ve destroyed the object using unset(). Before it is destroyed, the destructor calls thedisconnect() method and prints a message, which you can see in the comments.
Property Overloading
Note: PHP’s version of “overloading” is not quite the same as most other languages, though the same results can be reached.
This next set of magic methods are
补充:Web开发 , php ,