[英]PHP How to detect if method is being called from public or private scope?
How can you detect if a method is being called from within a public, private or protected scope?如何检测方法是从公共、私有还是受保护范围内调用的?
For example ...例如 ...
class Foo {
public function getPassword(){
$scope = [??????];
switch($scope){
case 'public':
return "*****";
break;
case 'protected': case 'private':
return "IamPassword";
break;
}
}
}
Inside the class I might need a property that might not be visible for the template engine but accessible by the class.在类中,我可能需要一个对模板引擎可能不可见但可由类访问的属性。
First of all I would strongly recommend you to redesign your code as soon as possible.首先,我强烈建议您尽快重新设计代码。 But nevertheless your question seemed interesting to me that is why you may try this:
但是你的问题对我来说似乎很有趣,这就是为什么你可以尝试这个:
$scopeIsInner = false;
$exception = new Exception();
$trace = $exception->getTrace();
$class = $trace[1]['class'];
if ($class == __CLASS__) {
$method = $trace[1]['function'];
$reflect = new ReflectionObject($this);
$methodList = $reflect->getMethods(ReflectionMethod::IS_PROTECTED | ReflectionMethod::IS_PRIVATE);
foreach ($methodList as $reflectionMethod) {
if ($method == $reflectionMethod->name) {
$scopeIsInner = true;
break;
}
}
}
var_dump($scopeIsInner);
PS I would never use this code in my own application PS 我永远不会在我自己的应用程序中使用此代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.