Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a class is an internal class or a user class?

Tags:

php

Is there a way in PHP to tell (programmatically, obviously) if a given class is an internal class (such as DateTime) or a user class (class MyClass)?

In case you wonder (and I'm sure you do), this is because ReflectionClass::newInstanceWithoutConstructor() throws an exception when used on internal classes, and as I'm writing a library to deep-copy objects, it must skip these internal classes.

Yes, I could just catch the ReflectionException, but this exception is thrown for other reasons as well (such as a non-existing class), and is not thrown for all system classes. so it's not exactly fulfilling my needs.

like image 453
BenMorel Avatar asked Jun 06 '13 11:06

BenMorel


1 Answers

A cleaner solution than using shell_exec whould be to use reflection:

$reflection = new ReflectionClass('SomeClass'); 
if($reflection->isUserDefined()) {
   // 'SomeClass' is not an PHP internal
}

Instead of an string ('SomeClass') you can also pass an object. For more information lookup Reflection and ReflectionClass::isUserDefined() in the PHP Manual

like image 138
MarcDefiant Avatar answered Oct 25 '22 19:10

MarcDefiant