Configure HTML/JavaScript

Showing posts with label Objects and references php. Show all posts
Showing posts with label Objects and references php. Show all posts

Tuesday, October 23, 2012

Passing Objects as parameters in PHP


Objects are Passed by reference by default:

By default the php objects are passed by reference below example will make it more clear. that is why when we copy object it property's are pointing to the same reference

class {
    public 
$foo 1;

$a = new A;$b $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = 
$b->foo 2;
echo 
$a->foo."\n";  //this will output 2 as the reference is copied
                    //$a and $b is point to the same location

$c = new A;$d = &$c;    // $c and $d are references
             // ($c,$d) = 
$d->foo 2;
echo 
$c->foo."\n";

$e = new A;

function 
foo($obj) {
    
// ($obj) = ($e) = 
    
$obj->foo 2;
}
foo($e);
echo 
$e->foo."\n";
?>

the output of the above sample example will
2
2
2



/*
 * Created on Oct 24, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

 class ClassTesting {
 
  private $foo;
 
  function __construct($foo){
  $this->foo = $foo;
  }
 
  private function ent($foo){
  $this->foo = $foo;
  }
 
  public function ret($obj){
  $obj->foo = 'this';
  var_dump($obj->foo);
  }
 }

 $x = new ClassTesting("man");
 $a = new ClassTesting("dog");
 $x->ret($a);

?>