2

我读过最好将类的属性设为私有,并使用 get/set 方法来访问/更改它们。

所以我以这种方式设置了一个类,但我希望能够在 html 表格中显示属性,我打算使用单独的 htmlTable 显示类来完成它。

我想到了4种可能。如果您已经知道执行此操作的理想方法,请随意跳过它们。

谢谢你。

可能性:

  1. 我可以使用以下方法获取类字段:

    $class_Vars = get_class_vars($object_class);
    $fields = $class_vars['fields'];
    
    // But as far as iterating through each object, this doesn't work:
    
    foreach($object_array as $current_object) {
        foreach($current_object as $value) {
            $html = '<td>' . $value . '</td>';
        }
    }
    

    这些值是私有且不可访问的。

  2. 一个看起来非常笨拙并且可能是调试噩梦的可能解决方案是:

    foreach($fields as $value) {
        $get_func = 'get' . ucwords($value); // e.g. $get_func = 'getId'
        $current_value = $current_object->$get_func();
    }
    

    我认为它会起作用,但它不适合我。

  3. 界面。另一种可能性是将 htmlTable 函数写入我想要执行的每个类中。但这是很多代码重用。

  4. 界面。或者我可以在export()每个类中写入一个函数,该函数只输出一个带有属性名称和值的数组。然后我的 htmlTable 类可以处理这些输出。

4

1 回答 1

1

将它们公开或制作get/set方法。

您还可以创建一个getAll()方法,该方法返回一个包含所有私有变量的关联数组。

于 2012-04-19T05:19:49.997 回答