php,如何创建父对象

发布于 2024-08-06 08:50:27 字数 190 浏览 2 评论 0原文

我想知道是否可以用 php 创建父对象,我已经尝试过:

new parent::__construct($var);

但它不起作用,并且我在 php 日志中收到以下错误:

(..)PHP 解析错误:语法错误、意外的 T_STRING、期望 T_VARIABLE 或 '$'(..)

I would like to know if there is anyway I can make a parent object with php, I have tried this:

new parent::__construct($var);

but it doesn't work and I get the following error in the php logs:

(..)PHP Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$'(..)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我为君王 2024-08-13 08:50:28

这可能有效:

$parentClass = get_parent_class();
$parentObject = new $parentClass();

This might work:

$parentClass = get_parent_class();
$parentObject = new $parentClass();
海之角 2024-08-13 08:50:27

请参阅 http://uk.php.net/get_parent_class

<?php
class Foo {

}

class Bar extends Foo {
  protected $p;

  public function __construct() {
    $pc = get_parent_class();
    $this->p = new $pc;
  }
}

$bar = new Bar;
var_dump($bar);

(但不知怎的,我不明白为什么你会需要这样的东西,但也许这只是我......;-))

see http://uk.php.net/get_parent_class

<?php
class Foo {

}

class Bar extends Foo {
  protected $p;

  public function __construct() {
    $pc = get_parent_class();
    $this->p = new $pc;
  }
}

$bar = new Bar;
var_dump($bar);

(But somehow I fail to see why you would need something like that. But maybe that's just me.... ;-))

三人与歌 2024-08-13 08:50:27

只需调用父类的构造函数,如下所示:

$parentClassObject = new ParentClassName();

使用parent::__construct() 调用父类构造函数,因为它在 PHP 中不会自动完成。

Just call the constructor of the parent class like:

$parentClassObject = new ParentClassName();

Use parent::__construct() to call the parent class constructor since it is not done automatically in PHP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文