【问题标题】:Child Constructor Not Maintaining Variables子构造函数不维护变量
【发布时间】:2013-02-08 14:58:12
【问题描述】:

我发现扩展抽象父类的子类存在一个奇怪的问题。
我这样称呼我的孩子班级:

$atts['ad_name'] = 'Test';
$atts['ad_type'] = $_REQUEST['ad_type'];
$add_ad = new wpam_ad_form( $atts );

我的子构造函数看起来像这样:

public function __construct( $atts ) {
    parent::__construct( $atts );
    echo "<br/><br/>New window child: " . $this->ad_new_window;
    echo "<br/>Ad Name child: " . $this->ad_name;
}

我的(简化的)父构造函数如下所示:

$this->ad_type = $atts['ad_type'];
$this->ad_name = stripslashes_deep( $atts['ad_name'] );
$this->ad_content = stripslashes_deep( $atts['ad_content'] );
$this->ad_image = $atts['ad_image'];
$this->ad_url = $atts['ad_url'];
$this->ad_prehtml = stripslashes_deep( $atts['ad_prehtml'] );
$this->ad_posthtml = stripslashes_deep( $atts['ad_posthtml'] );
$this->ad_new_window = ( $atts['ad_new_window'] != "" ? $atts['ad_new_window'] : 1 );
$this->ad_active = ( $atts['ad_active'] != "" ? $atts['ad_active'] : 1 );
$this->ad_archived = 0;
$this->ad_checked = 0;

echo "<br/>New window parent: " . $this->ad_new_window;
echo "<br/>Ad name parent: " . $this->ad_name;

这些回声的输出给了我:

New window parent: 1
Ad name parent: Test

New window child:
Ad Name child: 

我以前从未见过这种情况。这些值被正确地传递到子构造函数和父构造函数中。父构造函数正在正确设置值。然后在父构造函数运行后,子构造函数的 $this 属性中没有值。是什么导致值没有从父类返回到子类?

【问题讨论】:

  • 父类中的属性是否有可能是私有的?

标签: php class constructor


【解决方案1】:

如果没有在父类中看到您的属性声明,则很难判断。但乍一看,这些属性可能已设置为 private,这限制了它们对该类本身(父类)的访问/可见性,并且任何扩展它的类都不能直接访问它们。

如果是这种情况,那么您可以根据需要将它们设置为 protectedpublic

有关这些关键字的更多信息,您可以查看documentation entitled "Visibility" 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2018-10-23
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多