Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get constants from a class excluding all constants that may have been descended from parents?

Tags:

oop

php

here in second example PDO is populating MyClass with it's constants, how to filter them out ?

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
like image 837
rsk82 Avatar asked Jul 06 '11 13:07

rsk82


1 Answers

AFAIK

function MyMethod() {
  $reflector = new ReflectionClass(__CLASS__);
  print_r(array_diff($reflector->getConstants(),$reflector->getParentClass()->getConstants()));
}
like image 189
Greenisha Avatar answered Oct 29 '22 01:10

Greenisha