Sử dụng _get() và _set() PHP (phần 4)

Sử dụng _get() và _set()

Ví dụ sau đây cho thấy _get() và _set() có thể được sử dụng để lưu giữ đặc tính không
tồn tại trong mảng private. Nó tạo có hiệu lực một class với số lượng có thể không hạn
chế các đặc tinh ảo được giữ an toàn khỏi các đặc tính thật của class. Kĩ thuật này có
thể được sử dụng để tạo class giữ dữ liệu có nguy cơ.
Lưu đoạn script sau thành get_set.php trong thư mục root của bạn và chạy nó trên trình
duyệt.

< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Using __get() and __set() < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Using __get() and __set() < /h1 >
< ?php
class Car {
public $manufacturer;
public $model;
public $color;
private $_extraData = array();
public function __get( $propertyName ) {
if ( array_key_exists( $propertyName, $this- > extraData ) ) {
return $this- > extraData[$propertyName];
} else {
return null;
}
}
public function __set( $propertyName, $propertyValue ) {
$this- > extraData[$propertyName] = $propertyValue;
}
}
$myCar = new Car();
$myCar- > manufacturer = “Volkswagen”;
$myCar- > model = “Beetle”;
$myCar- > color = “red”;
$myCar- > engineSize = 1.8;
$myCar- > otherColors = array( “green”, “blue”, “purple”);
echo “ < h2 > Some properties: < /h2 > ”;
echo “ < p > My car’s manufacturer is “ . $myCar- > manufacturer . “. < /p > ”;
echo “ < p > My car’s engine size is “ . $myCar- > engineSize . “. < /p > ”;
echo “ < p > My car’s fuel type is “ . $myCar- > fuelType . “. < /p > ”;
echo “ < h2 > The \$myCar Object: < /h2 > < pre > ”;
print_r( $myCar );
echo “ < /pre > ”;
? >
< /body >
</html>

Xem kết quả ảnh dưới:

script

Chia sẻ

Leave a Reply

Your email address will not be published. Required fields are marked *