PHP4からPHP5にかけて、大きく変化したところと言えば、本格的なオブジェクト指向言語になったことだと思います。
そこで、PHP5によるオブジェクト指向がどんなものかを試しにコーディングしてみました。
<?php
class PcShopping
{
public $item = "VAIO";
public $price = 100;
public static $parts = "memory";
function getPcTotal()
{
$tax = $this->price * 0.05;
return $this->price + $tax;
}
function getPcItem()
{
return $this->item;
}
}
class ShoppingInJapan
{
public $item;
public $price;
function __construct($item,$price)
{
$this->item = $item;
$this->price = $price;
}
function getTotal()
{
$tax = $this->price * 0.05;
return $this->price + $tax;
}
function getItem()
{
return $this->item;
}
function getPrice()
{
return $this->price;
}
}
class ShoppingInAmerica extends ShoppingInJapan
{
function getTotal()
{
$discount = $this->price * 0.2;
$tax = ($this->price - $discount) * 0.08;
return $this->price - $discount + $tax;
}
}
$result = new PcShopping();
print $result->item." is ".$result->getPcTotal()."\n";
print "Item is ".$result->getPcItem()."\n";
print "Parts is ".PcShopping::$parts."\n";
print "------------------------------------------\n";
$result = new ShoppingInJapan('DELL','1000');
print $result->getItem()." is ".$result->getTotal()."\n";
print "------------------------------------------\n";
$result = new ShoppingInAmerica('DELL','1000');
print $result->getItem()." is ".$result->getTotal()."\n";
print "Price is ".$result->getPrice()."\n";
print "------------------------------------------\n";
?>
うーん、やっぱりオブジェクト指向の真髄は継承なのかな。
これをコマンドラインで実行すると、
[admin@server04 PHP_OBJ]$ php5 test.php VAIO is 105 Item is VAIO Parts is memory ------------------------------------------ DELL is 1050 ------------------------------------------ DELL is 864 Price is 1000 ------------------------------------------
継承は強烈ですな。