PHP函数通过引用self :: $ menus传递

时间:2016-05-13 18:56:22

标签: php arrays

我昨天问了this个问题。答案解决了我的问题,但这就是我现在要处理的问题。

我班上有这个数组:

private static $menus = [];

这是addChild到这个数组的函数:

public static function addChild($item_id, $title, $url, $parent_id, &$array)
{
    $child = [
        "id" => $item_id,
        "title" => $title,
        "url" => $url,
        "children" => [],
        "parent" => $parent_id
    ];
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            self::addChild($item_id, $title, $url, $parent_id, $value);
        }
        if ($key == "id" && $value == $parent_id) {
            array_push($array["children"], $child);
        }
    }
}

此函数的最后一个参数是通过引用传递的数组。我想要的是从函数中删除此参数并使用相同类的静态数组作为引用。

以下是我尝试过的事情:

public static function addChild($item_id, $title, $url, $parent_id, &$array = self::$menus)

但是php不允许我这样做。

我也试过这个:

public static function addChild($item_id, $title, $url, $parent_id, &$array = null){
$array = self::$menus;

但是我收到了这个错误:

  

允许的内存大小为134217728字节耗尽(试图分配1159168字节)

我刚刚通过参考概念学习了这个传递,所以我不确定使用它或如何正确使用它有什么限制。任何帮助都可以节省我的一天。

2 个答案:

答案 0 :(得分:2)

你在这里作为递归调用传递它:

self::addChild($item_id, $title, $url, $parent_id, $value);

哪个可能更好:

static::addChild($item_id, $title, $url, $parent_id, $value);

如果没有传递任何内容,请使用static::$menus代替$array

public static function addChild($item_id, $title, $url, $parent_id, &$array=null)
{
    if($array === null) {
        $array = &static::$menus;
    }
    // other code
}

或者这可能会更好,因为你实际上需要一个数组:

if(!is_array($array)) {
    $array = &static::$menus;
}

然后对于主调用(不是递归),只省略$ array参数。

答案 1 :(得分:0)

静态方法只能访问静态方法或属性。

自键字将对象本身表示为实例。静态方法存在于裸类中。

所以不要使用self ::只使用static ::它应该完成工作。

这是一个完整的例子

class Test {
    private static $menus = [];
    // Here is a function to addChild to this array:

    public static function addChild($item_id, $title, $url, $parent_id, &$array = null)
    {
        if(is_null($array))
        {
            $array = &static::$menus;
        }
        $child = [
            "id" => $item_id,
            "title" => $title,
            "url" => $url,
            "children" => [],
            "parent" => $parent_id
        ];
        foreach ($array as $key => &$value)
        {
            if (is_array($value))
            {
                static::addChild($item_id, $title, $url, $parent_id, $value);
            }
            if ($key == "id" && $value == $parent_id)
            {
                array_push($array["children"], $child);
            }
        }
        if(empty($array))
        {
            $array["children"] = [ $child ];
        }
    }

    public static function getMenus() {
        return static::$menus;
    }

}

Test::addChild(1,1,1,1);
var_export(Test::getMenus());
相关问题