php – 如何从类中获取常量,排除可能来自父母的所有常量?

前端之家收集整理的这篇文章主要介绍了php – 如何从类中获取常量,排除可能来自父母的所有常量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在第二个例子中,PDO用它的常量填充MyClass,如何过滤掉它们?
class MyClass {
  const PARAM_1 = 1;
  const PARAM_2 = 2;
  const PARAM_3 = 4;

  function MyMethod() {
    $reflector = new ReflectionClass(__CLASS__);
    print_r($reflector->getConstants());
  }

}

$myInstance = new MyClass();
$myInstance->MyMethod();

//returns:
//Array
//(
//    [PARAM_1] => 1
//    [PARAM_2] => 2
//    [PARAM_3] => 4
//)

class MyClassPDO extends PDO {
  const PARAM_1 = 1;
  const PARAM_2 = 2;
  const PARAM_3 = 4;

  function MyMethod() {
    $reflector = new ReflectionClass(__CLASS__);
    print_r($reflector->getConstants());
  }

}

$myInstancePDO = new MyClassPDO('sqlite::memory:');
$myInstancePDO->MyMethod();

//Array
//(
//    [PARAM_1] => 1
//    [PARAM_2] => 2
//    [PARAM_3] => 4
//    [PARAM_BOOL] => 5
//    [PARAM_NULL] => 0
//    [PARAM_INT] => 1
//    [PARAM_STR] => 2
//    [PARAM_LOB] => 3
//    [PARAM_STMT] => 4
//    [PARAM_INPUT_OUTPUT] => -2147483648
//    [PARAM_EVT_ALLOC] => 0
//    [PARAM_EVT_FREE] => 1
//    [PARAM_EVT_EXEC_PRE] => 2
//....and so on
据我所知
function MyMethod() {
  $reflector = new ReflectionClass(__CLASS__);
  print_r(array_diff($reflector->getConstants(),$reflector->getParentClass()->getConstants()));
}
原文链接:https://www.f2er.com/php/136246.html

猜你在找的PHP相关文章