我应该在OOP中使用单个函数还是对象?

时间:2014-01-28 17:33:46

标签: php function oop object

我是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有点复杂,但你应该知道我的意思

3 个答案:

答案 0 :(得分:3)

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

我建议阅读像http://shop.oreilly.com/product/mobile/9780596007126.do这样的书,阅读Symfony2等流行框架的代码

答案 1 :(得分:2)

尝试这样的事情:

class StringUtil
{

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

}

它易于使用,是静态的。

echo StringUtil::escapeString($string);

答案 2 :(得分:1)

在这种情况下,我会说这最适合作为函数或作为类的公共静态方法,如果你有其他类似的方法要组成一个类库。但是,我不打算为这个方法上课。