【问题标题】:Use $this argument for toString method in parent in PHP在 PHP 的 parent 中使用 $this 参数作为 toString 方法
【发布时间】:2018-06-05 13:53:37
【问题描述】:

我想测试使用带有 $this 参数的 toString() 方法,只在我的所有对象中调用一次。 为此我有:

class A {
    public function toString($object) {
         $result = '<pre>';
         foreach ($object as $key => $value) {
            $result .= $key . ': ' . $value . '<br>';
         }
         $result .= '</pre>';
         return $result;
     }
}

class B extends A {
    public function toString() {
        parent::toString($this);
    }
}

但这给我一个:

严格标准:B::toString() 的声明应与 A::toString($object) 兼容

但是当我在 B 中使用带有 $this 参数的函数时,不允许使用 $this,而对于其他,则缺少该参数。

【问题讨论】:

  • 在 A 类中将对象传递给 toString() 的想法听起来是错误的。您应该在对象本身上有一个 toString() 方法,而不是按照您尝试的方式(即传递对象本身)。
  • 如果您觉得有必要走这条路,您最好的选择可能是将A::toString($object) 更改为称为_toString($object) 之类的受保护方法,然后使用B::toString() { parent::_toString($this); }
  • 总而言之 - 有许多内置方法可以完成类似于toString 中的循环的事情(它只会不处理深层对象)。考虑查看其中的一些,您可能会发现一些有用的东西:json_encode、var_export、serialize 浮现在脑海中——我相信还有其他的。
  • ...更不用说已经有一个__toString()魔术方法专门用于这种事情,它可以让你echo $object
  • 回显 $object 显示错误“可捕获的致命错误:类的对象无法转换为字符串”

标签: php object this


【解决方案1】:

您不能更改在父级中声明的方法的定义:

class B extends A {
    public function toString($object = array()) {
        parent::toString($this);
    }
}

编辑:向父函数添加默认参数

Class A {
    public function toString($object = array()) {
        ...
    }
}

【讨论】:

  • 我已经尝试过了,但我需要一个 $object 变量什么都没有
【解决方案2】:

我会像这样更改原始代码:

class A {
    public function toString($object = null) {
        if ($object == null) {
            return '';
        }

        $result = '<pre>';
        foreach ($object as $key => $value) {
            $result .= $key . ': ' . $value . '<br>';
        }
        $result .= '</pre>';
        return $result;
    }
}

class B extends A {
    public function toString($object = null) {
        if ($object == null) {
            $object = $this;
        }
        parent::toString($object);
    }
}

【讨论】:

    【解决方案3】:

    如果这种行为真的只会被 自身 上的 A 类(及其子类)使用,那么我会说使用 PHP 的魔术方法 __toString(),它本质上可用于任何类实例。

    class A {
        public $foo = 'foo'; // so we can see something from A in output
        public function __toString() {
            $result = '<pre>';
            foreach($this as $key => $value) {
                $result .= "$key: $value<br>";
            }
            $result .= '</pre>';
            return $result;
        }
    }
    
    class B extends A {
        public $bar = 'bar'; // so we can see something from B in output
        // nothing else to do here, really
    }
    
    $b = new B();
    echo $b;
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 2021-03-11
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多