带有 protected 数组属性的 php 继承让我非常头疼

标签 php arrays inheritance visibility protected

所以我决定用 PHP 创建一些类,这样我就可以使用

最佳答案

也许您不会在 AddItem 方法中更改类 itemArray 属性?

你有这个:

protected function AddItem($item) {
    $itemArray[$item->itemName] = $item;
    echo "AddItem <br />"; //ugly debug code
    var_dump($itemArray); //even more of it
    return true;
}

试试这个:

protected function AddItem($item) {
    // $this will change the class property :)
    $this->itemArray[$item->itemName] = $item;
    echo "AddItem <br />"; //ugly debug code
    var_dump($this->itemArray); //even more of it
    return true;
}

您不会在很多地方使用 $this,例如在 MenuItem->Build 方法中:

class MenuItem {
    public $order;
    public $target;
    public $itemName;

function __construct($itemName="", $target="", $order=0) {
    $this->order = $order;
    $this->target = $target;
    $this->itemName = $itemName;
}

public function Build() {
    // The $target and $itemName variables aren't inicialized
    //if $this->target is empty or $this->itemName is empty then return empty string (both must be present to generate an item)
    if(strcasecmp($this->target,"") == 0 || strcasecmp($this->itemName,"") == 0) { 
        return "";
    }
    return "<li><a href=\"" . $this->target . "\">" . $this->itemName . "</a></li>";
}
}

关于带有 protected 数组属性的 php 继承让我非常头疼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528833/

相关文章:

php - 按下按钮时如何获取提交类型按钮的ID

javascript - Magento 联系表 : How to stop submitting and sending hidden values to email

php - codeigniter 多个 OR 查询

javascript - 如何组织和缩小大量 javascript 文件?

javascript - 如何在 VueJS 中创建字符串数组?

java - 将自定义二维数组打印为矩阵

ruby - 在 Ruby 中使用委托(delegate)维护相同的类

javascript - 数组是否作为 JavaScript ECMAScript 兼容中的左值?

C++ - 虚拟析构函数和链接器错误

java - 通用 <T extends A> 类使用静态字段而不是 T 的静态字段