Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use get_declared_class() to only ouput that classes I declared not the ones PHP does automatically

Tags:

php

A little curious, but I want to make an array out of the classes that I have declared using something like this

foreach(get_declared_classes() as $class)
    $c[] = $class;


print_r($c);

the only problem with that is that I get something like on top of my loaded classes:

stdClass
Exception
ErrorException
Closure
DateTime
DateTimeZone
DateInterval
DatePeriod
LibXMLError
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
RuntimeException
OutOfBoundsException
OverflowException
RangeException
UnderflowException
UnexpectedValueException
RecursiveIteratorIterator
IteratorIterator
{...}
SQLiteResult
SQLiteUnbuffered
SQLiteException
SQLite3
SQLite3Stmt
SQLite3Result
XMLReader
XMLWriter
XSLTProcessor
ZipArchive

is there a function that only loads user specific classes rather than system loaded classes? or perhaps a condition statement that limits the foreach to list those classes?

like image 674
Eli Avatar asked Feb 02 '12 07:02

Eli


2 Answers

The Reflection API can detect whether a class is internal or not. ReflectionClass::isInternal Checks whether the class is internal, as opposed to user-defined:

$userDefinedClasses = array_filter(
    get_declared_classes(),
    function($className) {
        return !call_user_func(
            array(new ReflectionClass($className), 'isInternal')
        );
    }
);

The code above will check and remove each class returned by get_declared_classes that is internal, leaving only the user defined classes. This way, you dont need to create and maintain an array of internal classes as was suggested elsewhere on this page.

like image 89
Gordon Avatar answered Sep 30 '22 17:09

Gordon


There is no built-in function to achieve this, but you can get_declared_classes just before you declare anything and store it in global variable, say $predefinedClasses. Then, where you need use:

print_r(array_diff(get_declared_classes(), $predefinedClasses));
like image 36
dmitry Avatar answered Sep 30 '22 17:09

dmitry