Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object assignments in PHP

Tags:

object

oop

php

I am a PHP learner. Please help me on the PHP OOP Code below :

class x{}
$x = new x; 
$x->name = "Chandan";

class y extends x {}  // Inheritance
$y = new y;

var_dump($x);   // object X; Shows Name property
var_dump($y);   // object y; Empty

$y = $x; 
var_dump($x);   // object X; name = chandan
var_dump($y);   // object X; name = chandan

$x->name = "Debasis";
var_dump($x);   // object X; name = debasis
var_dump($y);   // object X; name = debasis

Questions :

  1. When we say $x->name = "Chandan"; does it create a public properties? Never seen such assignments in C++.

  2. Changes to $x->name is also reflected in $y object.. why? $y = $x should create a copy of $x.

like image 976
user2314576 Avatar asked Jul 27 '26 06:07

user2314576


1 Answers

If you want to create a dynamic object:

$obj = new STDClass(); //Just a simple container, pretty much like array
$obj->anyStuff = "string" ; //Declare some public variables outside the class.

Otherwise you have to declare variables in your class explicitly.

Also, objects are always passed by reference (or assigned), because $obj in fact is not an object, it is just a reference, a link to it. The object itself is contained in memory.

$another = $obj ; Will just create another reference to the same object.

To clone object you must use: $clone = clone $obj ;

Also you can define a magic method __clone() that may be executed when cloning an object.

More info http://php.net/manual/en/language.oop5.cloning.php

like image 140
sybear Avatar answered Jul 29 '26 22:07

sybear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!