PHP Object Question
Unfortunately I cannot provide any code examples, however I will try and create an example. My question is about Objects and memory allocation in PHP.
If I have an object, lets say:
$o开发者_运维问答bject = new Class();
Then I do something like
$object2 = $object;
What is this actualy doing? I know there is a clone function, but thats not what I'm asking about, I'm concerned about whether this is creating another identical object, or if its just assigning a reference to $object.
I strongly understand this to mean that it just creates a reference, but in some case usages of mine, I find that I get another $object created, and I can't understand why.
If you use the magic method __invoke
, you can call an object similar to a function, and it will call that magic method.
class Object{
function __invoke(){ return "hi"; }
}
$object = new Object;
$object2 = $object();
echo $object2; // echos hi
That means that $object2
is equal to whatever that function returns.
Basically, you are calling a function, but using a variable as it's name. So:
function test(){ echo "hi"; }
$function_name = "test";
$function_name(); // echos hi.
In this case, you are just calling an object instead.
So, in reference to your question, this is actually not 'cloning' at all, unless the __invoke()
function looks like this:
function __invoke(){ return this }
In which case, it would be a reference to the same class.
You are creating a second reference of the same object. Here is a proof:
<?php
class TestClass {
private $number;
function __construct($num) { $this->number = $num; }
function increment() { $this->number++; }
function __toString() { return (string) $this->number; }
}
$original = new TestClass(10);
echo "Testing =\n";
echo "--------------------------------\n";
echo '$equal = $original;' . "\n";
$equal = $original;
echo '$equal = ' . $equal . ";\n";
echo '$original->increment();' . "\n";
$original->increment();
echo '$equal = ' . $equal . ";\n";
echo "\n";
echo "Testing clone\n";
echo "--------------------------------\n";
echo '$clone = clone $original;' . "\n";
$clone = clone $original;
echo '$clone = ' . $clone . ";\n";
echo '$original->increment();' . "\n";
$original->increment();
echo '$clone = ' . $clone . ";\n";
Use clone
if you want to create a copy of an instance.
Assuming that you mean
$object2 = $object;
And not
$object2 = $object();
PHP will create a reference to the original object, it will not copy it. See http://www.php.net/manual/en/language.oop5.basic.php, the section called Object Assignment.
<?php
class Object{
public $value = 1;
public function inc(){
$this->value++;
}
}
$object = new Object;
$object2 = $object;
$object->inc();
echo $object2->value; // echos 2, proving it's by reference
精彩评论