Skip to content
PHP Logo

Is it more efficient to check object types within a class or in the application using the class?

It is generally more efficient to check object types within a class rather than in the application using the class. This is because the class itself has more knowledge about its internal structure and can perform type checking more efficiently. Additionally, encapsulating the type checking within the class helps to keep the codebase clean and organized.

php
class MyClass {
    public function doSomething($obj) {
        if ($obj instanceof SomeClass) {
            // Perform actions specific to SomeClass
        } else {
            // Handle other cases
        }
    }
}