我问我的问题,我想在php变量中检测必须是一个对象或数组...
这是我的代码: Dispatcher.php
<?php
class Dispatcher {
var $request;
public function __construct(){
$this->request = new Request();
var_dump($this->request->query);
}
}
?>
Request.php
<?php
class Request {
public $query = false;
public function __construct(){
if(!empty($_GET)){
$this->query = array();
foreach($_GET as $k => $v) {
$this->query[$k] = $v;
}
//I need help here for mix array and stdClass();
}
}
}
?>
我还想使用$this->request->query['page']
(数组)和对象:$this->request->query->page
和stdClass();
但我不知道该怎么做......
感谢您帮助......:)
(抱歉我的英语不好,我和法国人一样;)......)
答案 0 :(得分:0)
尝试类似:
if(is_array($this->request->query))
{
echo $this->request->query['page'];
}
elseif(is_object($this->request->query))
{
echo $this->request->query->page;
}
else
{
echo "not array or object";
}
答案 1 :(得分:0)
您可以使用强制转换将数组转换为对象(我认为从PHP 5.4开始)。
对于对象(stdclass),它不会造成任何伤害。
$arr = array('foo'=>'bar');
$obj = (object) $arr;
echo $obj->foo;
答案 2 :(得分:0)
$this->query = new ArrayObject($_GET, ArrayObject::ARRAY_AS_PROPS);
// use it in dispatcher
echo $this->request->query['page'];
echo $this->request->query->page;
// your also able to iterate
foreach ($this->request->query as $key => $value) {
echo $key.'=>'.$value.'<br>';
}