0

这是我的 php 类:

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 中正常吗?我还能做些什么来得到我想要的吗?
谢谢!

4

1 回答 1

1

mysqli_fetch_object()创建一个对象时,它基本上会创建一个stdClass包含所有属性集的第一个对象,然后将对象的类切换到您提供的类,然后运行构造函数。正如您所注意到的,该__set()方法没有被调用,但这是正常的,也是该函数的工作原理。

于 2012-11-15T16:55:08.490 回答