使用静态方法调用(PHP)从数组数组创建对象数组

时间:2014-10-08 23:47:13

标签: php class static

我有一个这样的数组:

// Define pages
$pages = array(
    "home" => array(
        "title" => "Home page",
        "icon" => "home"
    ),
    "compositions" => array(
        "title" => "Composition page",
        "icon" => "music"
    ),
);

我想要完成的是:

$navigation = Utils::makeNavigation($pages);

,创建$navigation作为对象数组,以便我可以在视图中解析它 像这样:

foreach($navigation as $nav_item){
    echo $nav_item->page; // home(1st iter.), compositions(2nd iter.)
    echo $nav_item->title;// Home page, Composition page
    echo $nav_item->icon; // home, music
}

static Util-like-class是否适合此类问题?

修改

我想出了类似的东西,这看起来好吗?

<?php
class Utils {

    protected static $_navigation;

    public static function makeNavigation($pages = array()){

        if (!empty($pages)){
            foreach ($pages as $page => $parts) {
                $item = new stdClass;
                $item->page = $page;

                foreach ($parts as $key => $value) {
                    $item->$key = $value;
                }
                self::$_navigation[] = $item;
            }
        return self::$_navigation;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

假设您在代码中手动创建数组,只需转换为对象:

$pages = array(
    "home" => ( object ) array(
        "title" => "Home page",
        "icon" => "home"
    ),
    "compositions" => ( object ) array(
        "title" => "Composition page",
        "icon" => "music"
    ),
);

这将允许像对象一样访问它们:

$pages->home->title;

或像这样循环遍历:

for ( $pages as $pageName => $pageObject ) echo $pageName . " has title: " . $pageObject->title;

答案 1 :(得分:0)

我将创建作为类的静态成员包含在一起,以保持特定于类的代码:

class NavItem
{
//  Static member does not require an object to be called
static function create ($def)
{
    $ret = array ();
    foreach ($def as $idx=>$navDef)
        $ret [$idx] = new NavItem ($navDef);
    return $ret;
}
function __construct ($def)
{
    // Do something more specific with the current def (title, icon array)
    $this->param = $def;
}

function display ()
{
    //  Simple example
    echo $this->param ['title'];
    echo $this->param ['icon'];
}
    var                     $param;
};

//  Using your pages array as above
$pages = NavItem::create ($pages);
foreach ($pages as $idx=>$page)
    $page->display ();