【问题标题】:PHP - Overloaded class functionPHP - 重载的类函数
【发布时间】:2012-02-02 15:29:04
【问题描述】:

大家好。

我有一个类 MyClass 和一个函数 escape(),可以作为静态类或实例化对象调用。

MyClass::_escape('..... some string...');

$myclass->escape();

我想要的是在 staic 版本上没有 下划线 并且两者都具有相同的函数定义。我试着去做。

    class MyClass {

    public $_string = "";

      public function escape($string = null) {

            if($string == null) 
                  return new String(mysql_real_escape_string($this->_string));
            else
                  return new String(mysql_real_escape_string($string)); 

      }


   }

但是这个函数被 PHP 解析器失败了。有没有办法做我上面试图做的事情?

总而言之,我希望静态调用看起来像;

   print Myclass::escape('some string');

以及实例化调用的样子;

   print $myobject->escape(); //Which escapes the private variable _string

希望这很清楚。

问候

【问题讨论】:

  • 感谢大家的建议.. cmets。我每天都学得更多。 :)

标签: php function


【解决方案1】:
public function _escape($s){
  return self::escape($s);
}

【讨论】:

  • 所以你建议同时拥有这两个函数,但实例化的对象调用静态函数。如果是这样,这就是我目前拥有的,如果有相同的函数名就好了。 ..问候
  • 考虑到您损坏的设计,这是您最好的选择
  • 好的,所以不能使用相同的名称吗?我已经用 PHP 5 编码 2 个月了,只是想了解这些限制
【解决方案2】:

如果没有至少某种错误,您要实现的目标将无法实现:

示例使用static

error_reporting(E_ALL ^ E_STRICT);

class MyClass
{
  // note the *static* keyword
  public static function escape($string = null) {
    // $this is not defined, even if called as object-method 
    var_dump(isset($this));
  }
}

$foo = new MyClass();
$foo->escape(); // => bool(false)

MyClass::escape(); // => bool(false)

因此,如果您删除 static 关键字并重试,您将得到:

$foo->escape(); // => bool(true) 

还有:

Strict Standards: Non-static method MyClass::escape() should
not be called statically ...

MyClass::escape(); // => bool(false) 

【讨论】:

    【解决方案3】:

    您发布的代码中没有解析错误。实际上,只要您在对象上下文中从未将 $string 传递给 escape() 方法,它就可以按照您的意愿工作:

    $foo = new MyClass();
    $foo->_string = 'foo';
    $foo->escape(); // This works.
    MyClass::escape('bar'); // This works, too.
    $foo->escape('baz'); // Don't do this.  It'll escape $string instead of $this->_string.
    

    您可以通过escape() 方法中的determining whether or not you're in a static context 解决此问题,而不是检查$string 的存在。

    【讨论】:

    • @IEnumerable:很高兴我能帮上忙。 :-)
    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 2011-06-09
    • 1970-01-01
    • 2011-06-03
    • 2017-01-24
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多