给定:
class myClass extends PhalconMvcModel
{
public $a;
protected $b;
private $c;
}
如何在 myClass 中测试$a是公开的、$b是受保护的以及$c是私有的?
您可以使用 ReflectionProperty -
class myClass
{
public $a;
protected $b;
private $c;
}
$obj = new myClass();
$reflect_a = new ReflectionProperty(get_class($obj), 'a');
$reflect_c = new ReflectionProperty(get_class($obj), 'c');
var_dump($reflect_a->isProtected());
var_dump($reflect_c->isPrivate());
根据结果,您可以隐藏或显示它们。
根据您的需求,您可以使用模型元数据。您可以在模型中获取模型的属性:
<?php
/**
* Posts Model
*
*/
class Posts extends PhalconMvcModel
{
public $id;
public $users_id;
public $categories_id;
public $title;
public $slug;
public $content;
public $number_views;
public $number_replies;
public $votes_up;
public $votes_down;
public $sticked;
public $modified_at;
public $created_at;
public $edited_at;
public $status;
public $locked;
public $deleted;
public $accepted_answer;
private $foo_bar;
}
在控制器中的某个位置:
var_dump($this->modelsMetadata->getAttributes(new Posts()));die;
输出:
array (size=18)
0 => string 'id' (length=2)
1 => string 'users_id' (length=8)
2 => string 'categories_id' (length=13)
3 => string 'title' (length=5)
4 => string 'slug' (length=4)
5 => string 'content' (length=7)
6 => string 'number_views' (length=12)
7 => string 'number_replies' (length=14)
8 => string 'votes_up' (length=8)
9 => string 'votes_down' (length=10)
10 => string 'sticked' (length=7)
11 => string 'created_at' (length=10)
12 => string 'modified_at' (length=11)
13 => string 'edited_at' (length=9)
14 => string 'status' (length=6)
15 => string 'locked' (length=6)
16 => string 'deleted' (length=7)
17 => string 'accepted_answer' (length=15)
您还可以创建模型的方法:
public function getAttributes()
{
$metaData = $this->getModelsMetaData();
return $metaData->getAttributes($this);
}
PhalconMvcModelMetaData::getAttributes
返回表属性名称 - 表的字段。
此外,PHP 的 get_class_vars()
返回当前范围内可见的所有属性的数组。在您的情况下,它应该返回所有公共属性。