【问题标题】:Why can't we use the "new" keyword in a class property? [duplicate]为什么我们不能在类属性中使用“new”关键字? [复制]
【发布时间】:2012-02-18 10:52:15
【问题描述】:

可能重复:
Instance as a static class property

我遇到了一个关于在类中创建对象作为属性的问题。

include 'Bar.php';
class Foo()
{
    private $bar = new Bar();
}

出现解析错误。但是当我把 $bar 放在外部类时

include 'Bar.php';
class Foo()
{
    //private $bar = new Bar();
}
$bar = new Bar();

没有语法错误。完美运行。所以有什么问题。我只是将我的 Java 知识移植到 PHP。有时,它是如此令人困惑。

【问题讨论】:

  • 不可能;讨论了很久,看看:Why don't PHP attributes allow functions?
  • @Pekka:不知道。谢谢!
  • @Gordon 上面链接的问题是唯一接近规范解释尝试的问题。我不知道了;可能只是支持您的欺骗链接,以便它在关闭对话框中变得更加明显......您认为值得添加到标签维基吗?
  • @Pekka IMO 标签 wiki 毫无价值,因为没有人研究它,但可以肯定的是,继续添加它;)虽然我认为通过搜索更有意义,但劫持一个问题,重写它并将好的答案合并到其中。

标签: php


【解决方案1】:

你必须把它放入构造函数中:

class Foo() {
    private $bar;
    function __construct() {
        $this->bar = new Bar();
    }
}

【讨论】:

  • 抽象/基类的对象属性必须在每个继承类的每个构造函数中初始化。很烦人。
  • 只需调用父构造函数,它就会完成这项工作......
  • 很好,但很容易忘记这一点。
【解决方案2】:
class Foo {
    private $bar;

    public function __construct() {
      $this->bar = new Bar();
    }

    public function check() {
      return $this->bar->checkBack();
    }
}

class Bar {
  public function __construct() {
    print "good\n";
  }

  public function checkBack() {
    return "checked";
  }
}

$f = new Foo();
print $f->check();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2013-03-16
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多