Object-Oriented PHP

From Schmid.wiki
Jump to: navigation, search

Objects in PHP4

This simple example shows the pass-by-value semantics of PHP4:

<?php
class Container {
    var $items = array();
    function add($thing) { array_push($this->items, $thing); }
    function show() {
        foreach($this->items as $item) {
            $item->show();
        }
    }
}
class Thing {
    var $x = 0;
     function modify() { $this->x += 1; }
     function show()   { echo "x=".$this->x; }
}

$test = new Thing();
$cont = new Container();
//$test->modify(); // result: x=1
$cont->add($test);
$test->modify(); // result: x=0 since we're modifying the original $test,
                 // not the one sent to $cont
$cont->show();
?>
Personal tools