【问题标题】:Should I use a single function or an object in OOP?我应该在 OOP 中使用单个函数还是对象?
【发布时间】:2014-01-28 17:33:45
【问题描述】:

我是 OOP 的新手,我想知道我应该使用单个函数还是对象。 我应该这样做吗:

class Escape_String{
    protected $string;

    function __construct($string){
        if(get_magic_quotes_gpc)
            return $string;
        else
            return addslashes($string);
    }
}

$string = new Escape_String($_GET['string']);

或者我应该只使用函数而不是对象? (像这样:)

escapeString($string){
    if(get_magic_quotes_gpc)
        return $string;
    else
        return addslashes($string);
}

$string = escapeString($_GET['string']);

当然,真正的对象 Escape_String/function escapeString 稍微复杂一点,但你应该明白我的意思

【问题讨论】:

  • 除了addslashes 之外,Escape_String 对象还会做其他事情吗?因为如果不是这样,一个类似乎有点过头了。
  • 两者都不是。你想做的是错误的方法。使用PDO prepared statements
  • 已解决:我将创建一个名为“Escape”或类似的类,然后将多个静态函数放入其中用于不同的“类型”(MySQL 查询、字符串、数组等)跨度>
  • 我很惊讶没有人指出构造函数不能返回任何东西(当然,除了它们所属的类的实例)。
  • 谢谢指出,我不知道这个。

标签: php function oop object


【解决方案1】:

在你的情况下,最好将类命名为 StringUtils 并制作静态方法 escapeString

我建议阅读http://shop.oreilly.com/product/mobile/9780596007126.do 之类的书,并阅读 Symfony2 等流行框架的源代码

【讨论】:

    【解决方案2】:

    试试这样的:

    class StringUtil
    {
    
        static public function escapeString( $string )
        {
            if(get_magic_quotes_gpc) {
                return $string;
            } else {
                return addslashes($string);
            }
        }
    
    }
    

    它是静态的,易于使用。

    echo StringUtil::escapeString($string);
    

    【讨论】:

    • 您应该添加一些解释,说明为什么您为未来的用户使用静态方法。 +1
    【解决方案3】:

    在这种情况下,我会说这最适合作为函数或作为类上的公共静态方法,如果您有其他类似的方法要分组到类库中。但是,我不会只为这种方法创建一个类。

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 2018-10-23
      • 2012-01-19
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多