9

How can i check to see if a static class has been declared? ex Given the class

class bob {
    function yippie() {
        echo "skippie";
    }
}

later in code how do i check:

if(is_a_valid_static_object(bob)) {
    bob::yippie();
}

so i don't get: Fatal error: Class 'bob' not found in file.php on line 3

2 Answers 2

16

You can also check for existence of a specific method, even without instantiating the class

echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';

If you want to go one step further and verify that "yippie" is actually static, use the Reflection API (PHP5 only)

try {
    $method = new ReflectionMethod( 'bob::yippie' );
    if ( $method->isStatic() )
    {
        // verified that bob::yippie is defined AND static, proceed
    }
}
catch ( ReflectionException $e )
{
    //  method does not exist
    echo $e->getMessage();
}

or, you could combine the two approaches

if ( method_exists( bob, 'yippie' ) )
{
    $method = new ReflectionMethod( 'bob::yippie' );
    if ( $method->isStatic() )
    {
        // verified that bob::yippie is defined AND static, proceed
    }
}
Sign up to request clarification or add additional context in comments.

Comments

8

bool class_exists( string $class_name [, bool $autoload ])

This function checks whether or not the given class has been defined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.