PHP5を試してみる - 新しいオブジェクトモデルの採用
サンプルは、EXPERIENCEで実際に確認できるようにしてますので、気になる方は見てみてください。
実際にサンプルを実行しても「なんてことない」かも知れませんが、個人的には、これ(良い方の)インパクトが結構大きいです。ちなみに、PHP4の場合、Parse error: parse error, unexpected T_OBJECT_OPERATOR in factory_method.php on line 28となります。
●multiple_derefencing_of_objects_returned_from_methods.php
1: <?php
2: class Name {
3: function Name($_name)
4: {
5: $this->name = $_name;
6: }
7:
8: function display()
9: {
10: print $this->name;
11: print "\n";
12: }
13: }
14:
15: class Person {
16: function Person($_name, $_address)
17: {
18: $this->name = new Name($_name);
19: }
20:
21: function getName()
22: {
23: return $this->name;
24: }
25: }
26:
27: $person = new Person("John", "New York");
28: print $person->getName()->display();
29:
30: ?>
31: <hr>
32: <?php
33: show_source("./multiple_derefencing_of_objects_returned_from_methods.php");
34: ?>
これで、以前にご紹介したChain of Responsibilityパターンが以下のように書けます。
●ChainOfResponsibility.php
<?php
class CheckHandler
{
private $next_;
function setNext($next)
{
$this->next_ = $next;
return $this->next_;
}
:
}
:
$ch->setNext($cn)->setNext($ca)->setNext($cm);
:
?>
上のサンプルでは、クラスのメンバー変数を「private」宣言しているので、クラス外からはアクセスできなくなります。privateメンバーについては、こちらで取り扱っています。
|