douwei1174 2015-02-18 19:44
浏览 81

php中命名空间方法的动态实例化

There are few routers out there but I decided to create a very simple route for a very light site.

Here is my index.php

    $route = new Route();

    $route->add('/', 'Home');
    $route->add('/about', 'About');
    $route->add('/contact', 'Contact');

Here is my router:

<?php namespace Laws\Route;

use Laws\Controller\Home;

class Route
{
    private $_uri = array();
    private $_method = array();
    private $_route;

    public function __construct()
    {

    }

    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');
        if ($method != null) {
            $this->_method[] = $method;
        }
    }

    public function submit()
    {
        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

        foreach ($this->_uri as $key => $value) {
            if (preg_match("#^$value$#", $uriGetParam)) {
                $useMethod = $this->_method[$key];
                new $useMethod();     // this returns an error (cannot find Home'
                new Home(); // this actually works.
            }
        }
    }
}

new $useMethod(); does not work. returns error 'cannot find Home' new Home(); actually works.

What am I missing here?

  • 写回答

1条回答 默认 最新

  • dt2002 2015-02-18 20:01
    关注

    You can use your concurrent way for calling a class or you can use this:

    call_user_func(array($classname,$methodname))

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用