【问题标题】:PHP Automatic Properties / OverloadingPHP 自动属性/重载
【发布时间】:2010-09-28 01:47:19
【问题描述】:

我正在编写一些 PHP。我有几个类没有声明任何公共或其他属性。我有一个自定义的 mySQL 类,它从 mySQL 中获取对象并为新初始化的 PHP 对象设置属性值,如下所示...

while ($row = mysql_fetch_assoc($result))
{   
    foreach($row as $key => $value)
    {
        $this->{$key} = $value;         
    }
}

这似乎工作得很好,因为我可以在任何我喜欢的地方调用所述属性...$this->my_auto_property 等。我找不到任何将其描述为重载类对象属性的方式的 PHP 文档。

这样好吗?我想确保它不会在未来的 PHP 版本中消失的某种向后兼容性。

【问题讨论】:

    标签: php properties overloading


    【解决方案1】:

    这不是重载任何属性,它只是使用可变变量设置属性。动态创建新属性一直是 PHP 的一个特性。当然,没有人能保证它不会被弃用,但我认为 PHP 偏爱弱类型的方式不太可能。

    如果您想增加封装和对可访问性的控制,另一种方法是将值存储在数组中并创建一个魔术__get accessor 来读取它们。

    【讨论】:

    • 我第二次使用访问器重载以获得更多面向未来的保险。
    【解决方案2】:

    试试这样的:

    <?php
    /**
     * This class creates a dynamic shell to
     * define and set any Setter or Getter
     *
     * Example:
     *
     * $property = new DynamicProperties();
     * $property->setFax("123-123-1234"); // set[anything here first letter upper case]("value here")
     * echo $property->getFax()."\n"; // get[anything here first letter upper case]()
     */
    
    class DynamicProperties {
        private $properties;
    
        public function __call($name, $args) {
            if (preg_match('!(get|set)(\w+)!', $name, $match)) {
                $prop = $match[2];
                if ($match[1] == 'get') {
                    if (count($args) != 0) {
                        throw new Exception("Method '$name' expected 0 arguments, got " . count($args)."\n");
                    }
                    return $this->properties[$prop];
                } else {
                    if (count($args) != 1) {
                        throw new Exception("Method '$name' expected 1 argument, got " . count($args)."\n");
                    }
                    $this->properties[$prop] = $args[0];
                }
            } else {
                throw new Exception("Unknown method $name");
            }
        }
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2016-09-07
      • 2011-07-12
      相关资源
      最近更新 更多