【问题标题】:PHP implicit call of constructorPHP 隐式调用构造函数
【发布时间】:2013-10-28 22:21:58
【问题描述】:

我写了一个用整数初始化的类(类似于int的包装器):

class MyClass
{
    function __construct ($value)
    {
        // code, code, code
    }
}

我还写了一个函数,它接受这个类的对象作为参数:

class OtherClass
{
    public function foo (MyClass $obj)
    {
        // code, code, code
    }
}

这个调用函数可以简单地从:

$bar = new OtherClass();
$bar->foo(new MyClass(17));

到:

$bar = new OtherClass();
$bar->foo(17);

?

【问题讨论】:

  • 然后去掉函数参数中的类型提示,或者在函数中实例化MyClass变量P.S:php.net/manual/en/language.oop5.typehinting.php
  • 这是可能的,但它实际上使您的代码不太清晰。就目前而言,您确实知道您的foo 方法使用MyClass 对象。如果没有这种明确性,依赖关系将被隐藏。
  • 我认为您正在尝试使用 MyClass 扩展类 OtherClass。您应该阅读以下内容:php.net/manual/en/keyword.extends.php

标签: php constructor implicit-conversion


【解决方案1】:

你可以做类似的事情:

class OtherClass
{
    public function foo ($value)
    {
        $obj = new MyClass($value)
        // code, code, code
    }
}

但正如其他人提到的,它不太清楚......

【讨论】:

  • 没错,确实不太清楚。我认为有可能以某种方式强制 PHP 进行从 int 到 MyClass 的隐式转换(如在 C/C++ 中)而不修改 MyClass 和 OtherClass。
猜你喜欢
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多