PHP 怎么限制一个函数或者方法的某参数必须是一个类的静态属性?

2014 年 7 月 3 日
 displayabc
例如:

class config
{
public static $message =1;
}

function a($b){}

a(config::$message);


我如果能够使调用a函数时,传入的参数必须是config里的一个属性?
3924 次点击
所在节点    PHP
18 条回复
zaishanfeng2014
2014 年 7 月 3 日
反射,可以吗?
foccy
2014 年 7 月 3 日
有这样的需求,我觉得你应该在函数内检查。
likexian
2014 年 7 月 3 日
$a = new ReflectionProperty('config', 'message');
var_dump($a->isStatic());

请叫我PHP大神然后点赞
likexian
2014 年 7 月 3 日
好吧,我看错了,无视我吧
displayabc
2014 年 7 月 3 日
@likexian a(config::$message); 这样我在a函数内获取到的值是1
likexian
2014 年 7 月 3 日
你往a传入的是个数值了,数值就是数值,他来自哪里是没有标记的,反射是反射不了了
所以,你的需求基本上无解
wesley
2014 年 7 月 3 日
function a($b){
return property_exists(config,$b);
}
minbaby
2014 年 7 月 3 日
displayabc
2014 年 7 月 3 日
@minbaby 可能你没明白我在说什么
foccy
2014 年 7 月 3 日
这样?
public function a($b)
{
$hit = false;
$reflection = new ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if ($property->isStatic()) { // 限制静态属性
if ($b === $property->getValue()) {
$hit = true;
}
}
}
if (!$hit) {
throw new Exception('参数不在对象属性中');
}
}
displayabc
2014 年 7 月 3 日
@foccy 如果属性的值为1 ,那我直接传入1你这样判断不出来
minbaby
2014 年 7 月 3 日
@haython function 中你得到的参数是值,
而你想要的是验证参数是 config 类的属性,
那么肯定不能直接直接根据参数来判断,
非要实现这个东西的话,我觉得只能改写方法,
function a($class, $property){}
类似,才能判断,
wesley
2014 年 7 月 3 日
$a = new ReflectionClass('config');
print_r( $a->getStaticProperties() );
foccy
2014 年 7 月 3 日
@haython 那是我理解错你的需求了,这样目前来说我还不清楚。
dorentus
2014 年 7 月 3 日
你这背后的真实需求是什么?
Actrace
2014 年 7 月 3 日
<?php
class type_a{
public $val = 1;
}

function main(type_a $object){
var_dump($object);
}

$new_type_a = new type_a;
main($new_type_a);
//结果会是
//object(type_a)#1 (1) {
// ["val"]=>
// int(1)
//}

//如果你给的参数不是type_a类产生的对象.

$new_object = 1;//实际上 int 是一种内置类型
main($new_object);
////这将会报错
//Catchable fatal error: Argument 1 passed to main() must be an instance of type_a, integer given
Actrace
2014 年 7 月 3 日
可以要求参数为具体类(string,int,function都是内置的类),不过没有尝试过具体到属性.你可以在实现的内部指定目标属性,需要自己检查.
根据上面的帖子,稍微改下.
function main(type_a $object){
isset($object->val);
}
SoloCompany
2014 年 7 月 3 日
如果你的真实需求是 enum,那么请使用真正的 enum
另外,这种典型的 ab 问题还是少出显得好

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.xtra.eu.org/t/120826

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX