gpt4 book ai didi

php - 无法从子对象访问父变量

转载 作者:行者123 更新时间:2023-12-04 15:59:46 26 4
gpt4 key购买 nike

我试图找出为什么 Controller 类无法访问它扩展的父类的属性。

使用 $this 检索运输方式不会输出任何内容。 var_dump表示它是一个字符串长度为0的数组。

使用parent::返回错误“未定义的类常量'shipinfo'”

知道我做错了什么吗?我认为扩展父类时可以访问公共(public)/ protected 变量吗?

$data = trim(file_get_contents('php://input'));  
$link = new OrderLink($data);
$controller = new OrderLinkController();

class OrderLink{

protected $shipinfo = [
'name' => '',
'address' => '',
'unit' => '',
'city' => '',
'state' => '',
'country' => '',
'zip' => '',
'phone' => '',
'email' => '',
'method' => ''
];

protected $items;

function __construct($postdata)
{
$xml = simplexml_load_string($postdata);

$xml = $xml->Order;

$billinfo = $xml->AddressInfo[1];
$this->shipinfo['name'] = strval($billinfo->Name->Full);
$this->shipinfo['address'] = strval($billinfo->Address1);
$this->shipinfo['unit'] = strval($billinfo->Address2);
$this->shipinfo['city'] = strval($billinfo->City);
$this->shipinfo['state'] = strval($billinfo->State);
$this->shipinfo['country'] = strval($billinfo->Country);
$this->shipinfo['zip'] = strval($billinfo->Zip);

}
}

class OrderLinkController extends OrderLink
{

function __construct(){

echo 'Shipping Method: ' . $this->shipinfo['method'];
echo parent::shipinfo['method'];

if ($this->shipinfo['method'] == 'Local Pickup'){
$this->shipinfo['method'] = 'Pickup';

}
}
}

最佳答案

几个小问题:

  • 您需要调用父构造函数,因此您应该通过子构造函数将所需的 $postdata 传递到父构造函数中(或在子构造函数中创建它)
  • 您可以使用 $this-> 获取船舶信息

    class OrderLinkController extends OrderLink
    {

    function __construct($postdata){

    parent::__construct($postdata);

    echo 'Shipping Method: ' . $this->shipinfo['method'];
    echo $this->shipinfo['method'];

    if ($this->shipinfo['method'] == 'Local Pickup'){
    $this->shipinfo['method'] = 'Pickup';

    }
    }
    }

进一步说明:您不需要像前几行中那样实例化父级和子级:

$link = new OrderLink($data);
$controller = new OrderLinkController();

一旦子级的构造函数与父级的构造函数匹配,允许数据流动,您应该只实例化子级,通过子级的构造函数发送数据(请参阅我上面提供的代码以了解其工作原理):

$controller = new OrderLinkController($data);

关于php - 无法从子对象访问父变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39045933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com