FiftyStars
FiftyStars

Reputation: 328

PHP method exists in class without creating an object

In the input data I have file name, class name and method name. I need to check file existance(done) class existance(done) and method existance in this class without constructing. Is it possible?

Upvotes: 2

Views: 1247

Answers (3)

Josh Foskett
Josh Foskett

Reputation: 4121

You can append ::class (requires PHP 5.5+) to your class name, and perform the check like so:

<?php

class Test
{
    public function someMethod()
    {
        echo 'Hello, world.';
    }
}

var_dump(method_exists(Test::class, 'someMethod'));

Upvotes: 3

Alex
Alex

Reputation: 17289

http://ideone.com/3RIOcf

class my_class_name1 {

  public function  my_method_name1() {  

  }
}

$class_name = 'my_class_name';

$method_name = 'my_method_name';

echo class_exists($class_name)? ('Class '.$class_name.' exists'):('Class '.$class_name.' does not exist');
echo "\n";
echo class_exists($class_name.'1')? ('Class '.$class_name.'1'.' exists'):('Class '.$class_name.'1'.' does not exist');
echo "\n";
echo method_exists ($class_name.'1',$method_name)? ('Method '.$method_name.' exists in class '.$class_name.'1'):('Method '.$method_name.' does not exists in class '.$class_name.'1');
echo "\n";
echo method_exists ($class_name.'1',$method_name.'1')? ('Method '.$method_name.'1'.' exists in class '.$class_name.'1'):('Method '.$method_name.'1'.'does not exists in class '.$class_name.'1');

Upvotes: 0

M&#225;rcio Gonzalez
M&#225;rcio Gonzalez

Reputation: 1040

Try using reflection:

$method = null;

try{
    $class = new ReflectionClass('Your_Class');
    $method = $class->getMethod('Your_Method');
}
catch(Exception $e){
      echo $e->getMessage();
}

if($method != null){
     // your code here;
}

Upvotes: 3

Related Questions