note 104296 deleted from language.oop5.overloading by cmb
| From: | cmb@php.net | Date: | Sun, 29 Dec 2019 10:11:25 +0000 |
| Subject: | note 104296 deleted from language.oop5.overloading by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213661@lists.php.net to get a copy of this message | ||
Note Submitter: jk at jankriedner dot de
----
You should take care when using properties retrieved via __get() in functions that expect arguments
to be passed by reference (e.g. mysqli_stmt_bind_param). The reference is NOT set to the property
itself, but to the value returned by __get().
Thus, binding a property retrieved via __get() to a statement will let the statement be executed
always with the value the property had when calling bind_param, not with the current value it has
when calling execute().
E.g.:
<?php
error_reporting(E_ALL);
class foo {
protected $bar;
public function __construct() {
$this->bar = "Hello World!";
}
public static function factory() {
return new self;
}
public function __get($property) {
if(!property_exists($this,$property)) {
throw new InvalidArgumentException("Property {$property} doesn't exist");
}
return $this->$property;
}
public function setBar($value) {
$this->bar = $value;
}
}
$foo = new foo();
echo $foo->bar; // Ouputs: Hello World!
$db = new mysqli("localhost","root","","tests");
$sql = "INSERT INTO foo SET bar=?";
$res = $db->prepare($sql);
$res->bind_param("s",$foo->bar); // Notice: Indirect modification of overloaded
property foo::$bar has no effect in /var/www/overload.php on line 24
$res->execute(); // Writes "Hello World!" to database
$foo->setBar("Goodbye");
echo $foo->bar; // Outputs: Goodbye
$res->execute(); // Writes "Hello World!" to database
?>