Here is my php class:
class Category {
private $cat_id;
private $cat_name;
private $cat_is_main;
private $cat_parent;
function __get($key) {
switch ($key) {
case 'cat_id':
return $this->cat_id;
case 'cat_name':
return $this->cat_name;
case 'cat_is_main':
return $this->cat_is_main;
case 'cat_parent':
return $this->cat_parent;
}
}
function __set($key, $value) {
switch ($key) {
case 'cat_id':
$this->cat_id = (int) $value;
break;
case 'cat_name':
$this->cat_name = (string) $value;
break;
case 'cat_is_main':
$this->cat_is_main = (bool) $value;
break;
case 'cat_parent':
$this->cat_parent = (int) $value;
break;
}
}
}
$conn = new mysqli($server, $username, $password, $dbname);
if ($result = $conn->query('SELECT cat_id, cat_name FROM categories WHERE cat_id = 1;')) {
var_dump($result->fetch_object('Category'));
}
And I got:
object(Category)#5 (4) {
["cat_id":"Category":private]=> string(1) "1"
["cat_name":"Category":private]=> string(9) "test data"
["cat_is_main":"Category":private]=> string(1) "1"
["cat_parent":"Category":private]=> string(1) "0"
}
What I’m expecting is something like:
object(Category)#1 (4) {
["cat_id":"Category":private]=> int(1)
["cat_name":"Category":private]=> string(9) "test data"
["cat_is_main":"Category":private]=> bool(true)
["cat_parent":"Category":private]=> int(0)
}
It seem the mysqli_fetch_object() does not use my __set() method when create new object. It just some how set value for my private properties directly.
Is this normal in PHP? Is there anything else I can do to get what I want?
Thanks!
When
mysqli_fetch_object()creates an object, it basically creates astdClassfirst with all of the attributes set and then switches the object’s class to the one you supplied and then runs the constructor. As you noticed, the__set()method doesn’t get called, but that is normal and just how the function works.