/** * get callable methods within the classObj * * @param string|object $classObj * @param int $filter * @param bool $filterOwn * @return array array of \ReflectionMethod */ public function getCallableMethods($classObj, $filter, $filterOwn = true) { if (is_string($classObj) && !class_exists($classObj, false)) { throw new ClassNotDefinedException('Class name: ' . $classObj . ' not defined yet!'); } $className = $classObj; if (is_object($classObj)) { $className = get_class($classObj); } $reflectClass = new \ReflectionClass($classObj); $methods = array(); if (!$reflectClass->isUserDefined() || !$reflectClass->isInstantiable()) { return $methods; } $methods = $reflectClass->getMethods($filter); if ($filterOwn) { $needNeaten = false; foreach ($methods as $k => $method) { if ($method->class != $className) { unset($methods[$k]); !$needNeaten && ($needNeaten = true); } } $needNeaten && ($methods = array_values($methods)); } return $methods; }
function classData(ReflectionClass $class) { $details = ""; $name = $class->getName(); if ($class->isUserDefined()) { $details .= "{$name} is user defined\n"; } if ($class->isInternal()) { $details .= "{$name} is built-in\n"; } if ($class->isInterface()) { $details .= "{$name} is interface\n"; } if ($class->isAbstract()) { $details .= "{$name} is an abstract class\n"; } if ($class->isFinal()) { $details .= "{$name} is a final class\n"; } if ($class->isInstantiable()) { $details .= "{$name} can be instantiated\n"; } else { $details .= "{$name} can not be instantiated\n"; } return $details; }
/** * Returns inheritance inspection. * * The inspection result: * * must: * * * shortName * * name * * userDefined * * optional: * * * namespace * * @param \ReflectionClass $declaringClass ReflectionClass object. * @return array Inheritance inspection. */ protected function getInheritanceInspection(\ReflectionClass $declaringClass) { $inheritanceInspection = array('shortname' => $declaringClass->getShortName(), 'name' => $declaringClass->getName(), 'filename' => $declaringClass->getFileName(), 'userDefined' => $declaringClass->isUserDefined()); if ($declaringClass->inNamespace()) { $inheritanceInspection['namespace'] = $declaringClass->getNamespaceName(); } return $inheritanceInspection; }
private function getReflectionController($name) { $controllerName = __NAMESPACE__ . '\\' . $name . 'Controller'; if (!class_exists($controllerName, true)) { throw new NotFoundException("Controller {$controllerName} not found."); } $foundController = new \ReflectionClass($controllerName); if ($foundController->isAbstract() || $foundController->isInterface() || !$foundController->isUserDefined()) { throw new NotFoundException("Class {$controllerName} is not a correct controller class."); } return $foundController; }
private function build($parent, $items) { foreach ($this->all[$items] as $item) { $ref = new \ReflectionClass($item); if ($ref->isUserDefined()) { continue; } $p = $this->append($parent, array($item, $ref)); if (!empty($this->all[$item])) { $this->build($p, $item); } } }
function classData(ReflectionClass $class) { // получаем объект типа ReflectionClass $details = ""; $name = $class->getName(); if ($class->isUserDefined()) { $details .= "{$name} -- класс определён пользователем<br>"; } if ($class->isInterface()) { $details .= "{$name} -- это интерфейс"; } if ($class->isAbstract()) { $details .= "{$name} -- это абстрактный класс"; } if ($class->isFinal()) { $details .= "{$name} -- это финальный класс"; } if ($class->isInstantiable()) { $details .= "{$name} -- можно создать экземпляр класса"; } else { $details .= "{$name} -- нельзя создать экземпляр класса"; } return $details; }
public static function backupStaticAttributes(array $blacklist) { self::$staticAttributes = array(); $declaredClasses = get_declared_classes(); $declaredClassesNum = count($declaredClasses); for ($i = $declaredClassesNum - 1; $i >= 0; $i--) { if (strpos($declaredClasses[$i], 'PHPUnit') !== 0 && !$declaredClasses[$i] instanceof PHPUnit_Framework_Test) { $class = new ReflectionClass($declaredClasses[$i]); if (!$class->isUserDefined()) { break; } $backup = array(); foreach ($class->getProperties() as $attribute) { if ($attribute->isStatic()) { $name = $attribute->getName(); if (!isset($blacklist[$declaredClasses[$i]]) || !in_array($name, $blacklist[$declaredClasses[$i]])) { $attribute->setAccessible(TRUE); $backup[$name] = serialize($attribute->getValue()); } } } if (!empty($backup)) { self::$staticAttributes[$declaredClasses[$i]] = $backup; } } } }
<?php class userClass { public function userMethod($userParameter = 'default') { } } echo '<pre>'; // get_declared_classes() 获得已定义的类(系统类&&用户自定义的类) foreach (get_declared_classes() as $class) { $reflectionClass = new ReflectionClass($class); // isUserDefined() 检查是否是用户自定义的类 if ($reflectionClass->isUserDefined()) { Reflection::export($reflectionClass); } }
/** * Stops the collection of loaded classes and * returns the names of the files that declare the loaded classes. * * @return array */ public static function collectEndAsFiles() { $result = self::collectEnd(); $count = count($result); for ($i = 0; $i < $count; $i++) { $class = new ReflectionClass($result[$i]); if ($class->isUserDefined()) { $file = $class->getFileName(); if (file_exists($file)) { $result[$i] = $file; } else { unset($result[$i]); } } } return $result; }
print "\n"; print "--- isInterface() ---\n"; var_dump($rb->isInterface()); print "\n"; print "--- isInternal() ---\n"; var_dump($rb->isInternal()); print "\n"; print "--- isIterateable() ---\n"; var_dump($rb->isIterateable()); print "\n"; print "--- isSubclassOf() ---\n"; var_dump($rb->isSubclassOf('A')); var_dump($rb->isSubclassOf('C')); print "\n"; print "--- isUserDefined() ---\n"; var_dump($rb->isUserDefined()); print "\n"; print "--- newInstance() ---\n"; var_dump($rb->newInstance()); print "\n"; print "--- newInstanceArgs() ---\n"; var_dump($rb->newInstanceArgs()); print "\n"; print "--- get_defined_functions() ---\n"; $a = get_defined_functions()["user"]; sort($a); var_dump($a); print "--- get_defined_constants() ---\n"; $a = get_defined_constants(); print "SOME_CONSTANT: " . $a["SOME_CONSTANT"] . "\n"; if (isset($a["ANOTHER_CONSTANT"])) {
private function getExceptionData(ExceptionDataCollector $collector) { $exception = $collector->getException(); if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } $data = $exception->toArray(); foreach ($data as $nb => $exData) { // skip non-public exceptions $class = new \ReflectionClass($exData['class']); if ($class->isUserDefined() && !$this->isNamespaceWhitelisted($exData['class'])) { unset($data[$nb]); continue; } // skip built-in exceptions that are thrown from a non-public class if (!$class->isUserDefined() && (!isset($exData['trace'][1]) || !$this->isNamespaceWhitelisted($exData['trace'][1]['class']))) { unset($data[$nb]); continue; } foreach ($exData['trace'] as $key => $trace) { unset($data[$nb]['trace'][$key]['namespace'], $data[$nb]['trace'][$key]['short_class']); if ('' === $trace['class']) { $public = isset($exData['trace'][$key + 1]) && $this->isNamespaceWhitelisted($exData['trace'][$key + 1]['class']); } else { $public = $this->isNamespaceWhitelisted($trace['class']); } if (!$public) { foreach ($trace as $k => $v) { if (is_array($v)) { $data[$nb]['trace'][$key][$k] = array(); } else { if (is_string($v)) { if ('' !== $v) { $data[$nb]['trace'][$key][$k] = 'XXX'; } } else { $data[$nb]['trace'][$key][$k] = 'XXX'; } } } continue; } // additional heuristics for config data handling if ('Symfony\\Component\\DependencyInjection\\Loader\\YamlFileLoader' === $trace['class'] && 'parseImports' === $trace['function']) { $trace['args'] = array(array('array', array()), array('string', basename($trace['args'][1][1]))); } if ('Symfony\\Component\\Yaml\\Parser' === $trace['class'] && 'parse' === $trace['function']) { $trace['args'] = array(array('string', 'XXX')); } $data[$nb]['trace'][$key]['file'] = basename($trace['file']); $data[$nb]['trace'][$key]['args'] = $this->purgeArgsRecursive($trace['args']); } } return array_values($data); }
public static function backupStaticAttributes(array $blacklist) { self::$staticAttributes = array(); $declaredClasses = get_declared_classes(); $declaredClassesNum = count($declaredClasses); for ($i = $declaredClassesNum - 1; $i >= 0; $i--) { if (strpos($declaredClasses[$i], 'PHPUnit') !== 0 && strpos($declaredClasses[$i], 'File_Iterator') !== 0 && strpos($declaredClasses[$i], 'PHP_CodeCoverage') !== 0 && strpos($declaredClasses[$i], 'PHP_Invoker') !== 0 && strpos($declaredClasses[$i], 'PHP_Timer') !== 0 && strpos($declaredClasses[$i], 'PHP_TokenStream') !== 0 && strpos($declaredClasses[$i], 'Symfony') !== 0 && strpos($declaredClasses[$i], 'Text_Template') !== 0 && !$declaredClasses[$i] instanceof PHPUnit_Framework_Test) { $class = new ReflectionClass($declaredClasses[$i]); if (!$class->isUserDefined()) { break; } $backup = array(); foreach ($class->getProperties() as $attribute) { if ($attribute->isStatic()) { $name = $attribute->getName(); if (!isset($blacklist[$declaredClasses[$i]]) || !in_array($name, $blacklist[$declaredClasses[$i]])) { $attribute->setAccessible(TRUE); $value = $attribute->getValue(); if (!$value instanceof Closure) { $backup[$name] = serialize($value); } } } } if (!empty($backup)) { self::$staticAttributes[$declaredClasses[$i]] = $backup; } } } }
/** * Calculates the dependencies for this function or method. * */ protected function calculateDependencies() { foreach ($this->function->getParameters() as $parameter) { try { $class = $parameter->getClass(); if ($class) { $className = $class->getName(); if ($className != $this->scope && !in_array($className, $this->dependencies)) { $this->dependencies[] = $className; } } } catch (ReflectionException $e) { } } $inNew = FALSE; foreach ($this->tokens as $token) { if (is_string($token)) { if (trim($token) == ';') { $inNew = FALSE; } continue; } list($token, $value) = $token; switch ($token) { case T_NEW: $inNew = TRUE; break; case T_STRING: if ($inNew) { if ($value != $this->scope && class_exists($value, FALSE)) { try { $class = new ReflectionClass($value); if ($class->isUserDefined() && !in_array($value, $this->dependencies)) { $this->dependencies[] = $value; } } catch (ReflectionException $e) { } } } $inNew = FALSE; break; } } }
<?php // Copyright (c) 2014 Robin Bailey @ Dionach Ltd. $classlist = get_declared_classes(); // The methods we're interested in $magic = array("__wakeup", "__destruct", "__toString", "__get", "__set", "__call"); foreach ($classlist as $class) { $reflClass = new ReflectionClass($class); // Ignore classes from PHP core/extensions if ($reflClass->isUserDefined()) { foreach ($magic as $method) { try { if ($reflClass->getMethod($method)) { $reflMethod = new ReflectionMethod($class, $method); $parent = $reflMethod->getDeclaringClass()->getName(); $filename = $reflMethod->getDeclaringClass()->getFileName(); $startline = $reflMethod->getStartLine(); // If filename is not defined the class inherits from a core/extension class if ($filename) { // Get the source code of the method $exp = $reflMethod->export($class, $method, 1); // Extract the filename, start and end line numbers preg_match("/@@\\s(.*)\\s(\\d+)\\s-\\s(\\d+)/i", $exp, $matches); $source = file($filename); // -1/+1 to include the first and last lines, incase code is on same line as method declaration $functionBody = implode("", array_slice($source, $matches[2] - 1, $matches[3] - $matches[2] + 1)); // Check for interesting function calls if (preg_match("/eval|assert|call_user_func|system|popen|shell_exec|include|require|file_get_contents|unlink|exec/", $functionBody, $m)) { $interesting = $m[0]; } print $class . "::" . $method . "() ";
<?php $r1 = new ReflectionClass("stdClass"); var_dump($r1->isUserDefined('X')); var_dump($r1->isUserDefined('X', true));
function phantm_collect_state(array $vars) { $bt = debug_backtrace(); $file = $bt[0]['file']; $line = $bt[0]['line']; // remap global entries to superglobals $vars['GLOBALS']['GLOBALS'] =& $vars['GLOBALS']; $vars['GLOBALS']['_GET'] =& $vars['_GET']; $vars['GLOBALS']['_POST'] =& $vars['_POST']; $vars['GLOBALS']['_REQUEST'] =& $vars['_REQUEST']; $vars['GLOBALS']['_COOKIE'] =& $vars['_COOKIE']; $vars['GLOBALS']['_SESSION'] =& $vars['_SESSION']; $vars['GLOBALS']['_FILES'] =& $vars['_FILES']; $vars['GLOBALS']['_ENV'] =& $vars['_ENV']; $vars['GLOBALS']['_SERVER'] =& $vars['_SERVER']; if (ini_get('register_long_arrays')) { $vars['HTTP_GET_VARS'] =& $vars['_GET']; $vars['HTTP_POST_VARS'] =& $vars['_POST']; $vars['HTTP_ENV_VARS'] =& $vars['_ENV']; $vars['HTTP_COOKIE_VARS'] =& $vars['_COOKIE']; $vars['HTTP_SERVER_VARS'] =& $vars['_SERVER']; $vars['GLOBALS']['HTTP_GET_VARS'] =& $vars['_GET']; $vars['GLOBALS']['HTTP_POST_VARS'] =& $vars['_POST']; $vars['GLOBALS']['HTTP_ENV_VARS'] =& $vars['_ENV']; $vars['GLOBALS']['HTTP_COOKIE_VARS'] =& $vars['_COOKIE']; $vars['GLOBALS']['HTTP_SERVER_VARS'] =& $vars['_SERVER']; } $path = basename(basename($_SERVER['SCRIPT_FILENAME'])) . "--" . date('d-m-y--H\\hi\\ms') . ".dump"; $fh = fopen($path, "w"); if (!$fh) { die("Failed to write dump..."); } fwrite($fh, "# Dumped state of " . $file . " at line " . $line . " \n"); fwrite($fh, "# Date: " . date("r") . "\n"); fwrite($fh, "# Included files:\n"); $files = get_included_files(); foreach ($files as $f) { $f = realpath($f); if ($f === __FILE__ || $f === $file) { continue; } fwrite($fh, filemtime($f) . ":" . $f . "\n"); } fwrite($fh, "# Function declarations:\n"); $funcs = get_defined_functions(); foreach ($funcs['user'] as $f) { if ($f == 'phantm_incl' || $f == 'phantm_collect_state') { continue; } $rf = new ReflectionFunction($f); fwrite($fh, $f . ":" . $rf->getStartLine() . ":" . $rf->getFileName() . "\n"); } fwrite($fh, "# Classes declarations:\n"); $classes = get_declared_classes(); foreach ($classes as $c) { $rc = new ReflectionClass($c); if (!$rc->isUserDefined()) { continue; } fwrite($fh, $c . ":" . $rc->getStartLine() . ":" . $rc->getFileName() . "\n"); } fwrite($fh, "# Constants:\n"); $allConsts = get_defined_constants(true); $consts = !empty($allConsts['user']) ? $allConsts['user'] : array(); fwrite($fh, strtr(serialize($consts), array("\\" => "\\\\", "\n" => "\\n", "\r" => "\\r")) . "\n"); fwrite($fh, "# Heap state:\n"); unset($vars['GLOBALS']); fwrite($fh, strtr(serialize($vars), array("\\" => "\\\\", "\n" => "\\n", "\r" => "\\r")) . "\n"); fclose($fh); copy($path, "last.dump"); exit("\n--- phantm: Done recording state to " . $path . ", shutting down ---\n"); }
if ($argc < 2) { print "{$argv['0']}: classes1.php [, ...]\n"; exit; } // Include the files foreach (array_slice($argv, 1) as $filename) { include_once $filename; } // Get all the method and function information // Start with the classes $methods = array(); foreach (get_declared_classes() as $class) { $r = new ReflectionClass($class); // Eliminate built-in classes if ($r->isUserDefined()) { foreach ($r->getMethods() as $method) { // Eliminate inherited methods if ($method->getDeclaringClass()->getName() == $class) { $signature = "{$class}::" . $method->getName(); $methods[$signature] = $method; } } } } // Then add the functions $functions = array(); $defined_functions = get_defined_functions(); foreach ($defined_functions['user'] as $function) { $functions[$function] = new ReflectionFunction($function); }
<?php /** *@name :PHP利用反射机制获取用户自声明的类--反射API */ class UserClass { public function userMethod($userParameter = 'default') { } } foreach (get_declared_classes() as $class) { $reflection = new ReflectionClass($class); if ($reflection->isUserDefined()) { //判断是否是自声明的类 Reflection::export($reflection); //打印出该类的一些资料 } }
protected final function Instantiate($classname) { $classname = ucfirst(strtolower(trim($classname))); $classfile = PANEL_BASE_PATH . '/server/modules/comp/' . $classname . '.class.php'; if (is_file($classfile)) { require_once $classfile; } if (!class_exists($classname, false)) { exit('ERROR: ' . $classname . ' is not defined as a Class'); } $class = new ReflectionClass($classname); if (!$class->isSubclassOf('PanelCommon')) { exit("ERROR: {$classname} must extends PanelCommon"); } if (!$class->isUserDefined()) { exit("ERROR: {$classname} must be user defined and not internal to PHP"); } if (!$class->IsInstantiable()) { exit("ERROR: {$classname} must be instantiable and not an Interface or Abstract class"); } if (!$class->hasMethod('home')) { exit("ERROR: {$classname} lacks required method/function home()"); } if (!$class->hasProperty('menu')) { exit("ERROR: {$classname} lacks \$menu as a class property"); } return new $classname(); }
<?php class C { } $r1 = new ReflectionClass("stdClass"); $r2 = new ReflectionClass("ReflectionClass"); $r3 = new ReflectionClass("ReflectionProperty"); $r4 = new ReflectionClass("Exception"); $r5 = new ReflectionClass("C"); var_dump($r1->isUserDefined(), $r2->isUserDefined(), $r3->isUserDefined(), $r4->isUserDefined(), $r5->isUserDefined());
/** * Returns the names of the classes declared in a sourcefile. * * @param string $filename * @param string $commonPath * @param boolean $clearCache * @return array * @access public * @static */ public static function getClassesInFile($filename, $commonPath = '', $clearCache = FALSE) { if ($commonPath != '') { $filename = str_replace($commonPath, '', $filename); } if ($clearCache) { self::$fileClassMap = array(); } if (empty(self::$fileClassMap)) { $classes = get_declared_classes(); $count = count($classes); for ($i = 0; $i < $count; $i++) { $class = new ReflectionClass($classes[$i]); if ($class->isUserDefined()) { $file = $class->getFileName(); if ($commonPath != '') { $file = str_replace($commonPath, '', $file); } if (!isset(self::$fileClassMap[$file])) { self::$fileClassMap[$file] = array($class); } else { self::$fileClassMap[$file][] = $class; } } } } return isset(self::$fileClassMap[$filename]) ? self::$fileClassMap[$filename] : array(); }
/** * Returns <tt>true</tt> if this class is a synthetic class; * returns <tt>false</tt> otherwise. * @return <tt>true</tt> if and only if this class is a synthetic class as * defined by the Java Language Specification. * @since 1.5 */ public function isSynthetic() { return $this->reflectionClass->isUserDefined(); }
/** * Returns the names of the classes declared in a sourcefile. * * @param string $filename * @param string $commonPath * @param boolean $clearCache * @return array */ public static function getClassesInFile($filename, $commonPath = '', $clearCache = FALSE) { if ($commonPath != '') { $filename = str_replace($commonPath, '', $filename); } if ($clearCache) { self::$fileClassMap = array(); } if (empty(self::$fileClassMap)) { $classes = array_merge(get_declared_classes(), get_declared_interfaces()); foreach ($classes as $className) { $class = new ReflectionClass($className); if ($class->isUserDefined()) { $file = $class->getFileName(); if ($commonPath != '') { $file = str_replace($commonPath, '', $file); } if (!isset(self::$fileClassMap[$file])) { self::$fileClassMap[$file] = array($class); } else { self::$fileClassMap[$file][] = $class; } } } } return isset(self::$fileClassMap[$filename]) ? self::$fileClassMap[$filename] : array(); }
private final function LoadModule($classname) { if (!$this->modules) { $this->SessionDestroy(); $this->Login('ERROR: No modules defined.'); exit; } $classes = explode(' ', $this->modules); if (!in_array($classname, $classes)) { exit('ERROR: LoadModule found unknown Class/Module'); } $classfile = PANEL_BASE_PATH . '/server/modules/comp/' . $classname . '.class.php'; if (is_file($classfile)) { require_once $classfile; } if (!class_exists($classname, false)) { exit('ERROR: ' . $classname . ' is not defined as a Class'); } $class = new ReflectionClass($classname); if (!$class->isSubclassOf('PanelCommon')) { exit("ERROR: {$classname} must extends PanelCommon"); } if (!$class->isUserDefined()) { exit("ERROR: {$classname} must be user defined and not internal to PHP"); } if (!$class->IsInstantiable()) { exit("ERROR: {$classname} must be instantiable and not an Interface or Abstract class"); } if (!$class->hasMethod('home')) { exit("ERROR: {$classname} lacks required method/function home()"); } if (!$class->hasProperty('menu')) { exit("ERROR: {$classname} lacks \$menu as a class property"); } }
private static function getInterfaces(ReflectionClass $class) { $classes = array(); foreach ($class->getInterfaces() as $interface) { $classes = array_merge($classes, self::getInterfaces($interface)); } if ($class->isUserDefined() && $class->isInterface() && !isset(self::$seen[$class->getName()])) { self::$seen[$class->getName()] = true; $classes[] = $class; } return $classes; }
/** * @param string $className * * @return array(string) */ protected function getPublicMethods($className) { $phpversion = $reflection = new \ReflectionClass($className); $methods = array(); foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { $comment = $method->getDocComment(); if (!$method->isPublic() || $method->isStatic() || $reflection->isUserDefined() !== $method->isUserDefined() || $reflection->isInternal() !== $method->isInternal() || is_int(strpos($comment, '@access private'))) { continue; } $regexp = '(@since\\s+PHP (\\d+\\.\\d+\\.\\d+(\\-dev|RC\\d+|alpha\\d+|beta\\d+)?))'; if (preg_match($regexp, $comment, $match) && version_compare(phpversion(), $match[1]) < 0) { continue; } $methods[] = $method->getName(); } sort($methods); return $methods; }