【问题标题】:Static function behavior and __toString magic method静态函数行为和 __toString 魔术方法
【发布时间】:2015-01-04 07:58:25
【问题描述】:

这是我的代码的一个精简的 sn-p

namespace classes\tools\html;

class html{
    public static function element($tag) {
        return new element($tag);
    }
}

class element{


      //......

    public function __toString() {


        $element = "<$this->tag";
        foreach ($this->attributes as $attribute => $value) {
        $element.= " $attribute=\"$value\"";
        }
        if ($this->selfClosing) {
            $element.="/>";
            return $element;
        }

        $element.=">$this->html</$this->tag>";

        return $element;
    }

}


$html = new html();

让我感到困惑的是,如果我用以下方式调用元素:

$html::element('a')->attr('href','/home/')->html('home');

它会返回

'<a href="/home/">home</a>"

但如果我用以下方式调用它:

$html->element('a')->attr('href','/home/')->html('home');

它将返回一个element 对象

所以我的问题是为什么用:: 运算符静态调用它会调用__toString 方法而后者却没有?

编辑

link to full element class

【问题讨论】:

  • 尝试用var_dump()替换return,我的猜测是return在静态上下文中触发了__toString。然而,这是一个猜测,如果有人能给出更有根据的解释,我会非常高兴。
  • 顺便说一句非常有趣的问题
  • @Digitalis 是的,我可能应该提到我做了一个 var_dump,它显示了元素对象的内容
  • 那么我怀疑 return 语句在静态上下文中调用了 __toString。
  • It will return -- 这是什么意思?请添加获取输出值的方式。

标签: php oop static


【解决方案1】:

html 类的 element() 函数是静态的,所以你不想创建 html 的实例,而是像这样调用你的函数:

echo html::element('a')->...

有时需要强制转换返回值来获取字符串,因为元素函数返回一个元素对象:

$var = (string)html::element('a')->...

注意:请注意我不使用 $html

【讨论】:

  • 其实echo $html-&gt;element('span')...会调用to string方法,而$string= $html-&gt;element('span')...不会
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 2018-05-19
  • 1970-01-01
  • 2011-06-10
相关资源
最近更新 更多