0
這裏是我的PHP類($ CLASS_NAME)不使用__set()方法:mysqli_fetch_object時創建新的對象實例
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'));
}
而且我得到了:
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"
}
我很期待是這樣的:
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)
}
它似乎是mysqli_fetch_object()時創建新的對象不使用我的__set()方法。它只是一些如何爲我的私人財產直接設定價值。
在PHP中這是正常的嗎?還有什麼我可以做得到我想要的?
謝謝!
在對象的情況下,性能是不是人跡罕至,所以我想這是正常/預期的行爲'__set'不會被調用。你是否嘗試過使用構造函數? – jeroen
感謝您的諮詢!基於@ G-Nugget答案,現在我使用構造函數來檢查我的屬性。奇怪,但它的工作! – nvcnvn