Longhorn PHP 2025 - Speakers and Schedule Announced!

Voting

: three minus two?
(Example: nine)

The Note You're Voting On

tolgakaragol at gmail dot com
5 years ago
Here is a basic example about clone issue. If we use clone in getClassB method. Return value will be same as new B() result. But it we dont use clone we can effect B::$varA.

class A
{
protected $classB;

public function __construct(){
$this->classB = new B();
}

public function getClassB()
{
return clone $this->classB;
}
}

class B
{
protected $varA = 2;

public function getVarA()
{
return $this->varA;
}

public function setVarA()
{
$this->varA = 3;
}
}

$a = new A();

$classB = $a->getClassB();

$classB->setVarA();

echo $a->getClassB()->getVarA() . PHP_EOL;// with clone -> 2, without clone it returns -> 3

echo $classB->getVarA() . PHP_EOL; // returns always 3

<< Back to user notes page

To Top