我在扩展类中获得全局数组时遇到了麻烦。该数组由使用url传递的参数填充。
我得到我的url然后爆炸它。然后我将前两个参数设置为一个类和一个方法。然后重新设置数组键,以便参数从0开始。
例如:class App
{
protected $controller = '';
protected $method = '';
protected $param = [];
public function init()
{
if (isset($_GET['url'])) {
$url = explode('/', filter_var(trim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
else
{
header('Location: /home');
}
if (file_exists(APP . '/controllers/' . $url[0] . '.php'))
{
$this->controller = $url[0];
unset($url[0]);
}
else
{
if (DEVELOPMENT == true) {
var_dump($url);
}
else
{
header('Location: /home');
}
}
require_once 'controllers/' . $this->controller . '.php';
$className = ucfirst($this->controller);
$class = new $className;
if (isset($url[1]))
{
if (method_exists($className, $url[1]))
{
$this->method = $url[1];
unset($url[1]);
$methodName = $this->method;
$class->$methodName();
}
}
$GLOBALS['param'] = array_values($url);
}
public function view($view)
{
require_once VIEW . '/header.htm';
require_once VIEW . '/' . $view . '.htm';
require_once VIEW . '/footer.htm';
}
}
如果我的url是site/class/method/foo/bar我转储$GLOBALS['param']我得到
array (size=2)
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
这是好的和我想要的。
但是,如果我对扩展类做相同的转储。
class User extends App
{
public function __construct()
{
var_dump($GLOBALS['param']);
}
}
我的数组为空。我真正想做的是能够从任何控制器类的url中获取参数并使用它们。我该怎么做呢?
我错了。我通过使用call_user_func_array解析方法的参数来解决这个问题,如下所示
class App
{
protected $controller = 'home';
protected $method = 'index';
protected $params = [];
public function init()
{
$url = $this->parseUrl();
if (file_exists(APP . '/controllers/' . $url[0] . '.php'))
{
$this->controller = $url[0];
unset($url[0]);
}
require_once APP . '/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;
if (isset($url[1]))
{
if (method_exists($this->controller, $url[1]))
{
$this->method = $url[1];
unset($url[1]);
}
}
$this->params = $url ? array_values($url) : [];
// Parse params to method
call_user_func_array([$this->controller, $this->method], $this->params);
}
public function parseUrl()
{
if (isset($_GET['url']))
{
return $url = explode('/', filter_var(trim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
}
public function view($view)
{
require_once VIEW . '/header.htm';
require_once VIEW . '/' . $view . '.htm';
require_once VIEW . '/footer.htm';
}
}
然后我可以在扩展类
中获取参数class User extends App
{
public function index($var = '', $otherVar = '')
{
echo $var. $otherVar;
}
public function register()
{
$this->view('user-register');
}
public function login()
{
$this->view('user-login');
}
}