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 :
When we say $x->name = "Chandan"; does it create a public properties? Never seen such assignments in C++.
Changes to $x->name is also reflected in $y object.. why? $y = $x should create a copy of $x.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With