0

I have an array $run that hold $run[0] - class name and $run[1] - class method to run and i want to be able to do this :

// this is working ok
$class = new $run[0]();
// this is error
$class->$run[1]();

What is the best and most elegant way of doing this ?

Thanks

2

1 Answer 1

1

Add {} around $run[1]: This uses an anonymous class which is available since PHP >= 7.0

<?php
$run = [];
$run[0] = new Class {

    public function myMethod(){
        return 'Hello world';   
    }

};
$run[1] = 'myMethod';


$class = new $run[0]();
echo $class->{$run[1]}(); //Returns Hello world
Sign up to request clarification or add additional context in comments.

12 Comments

@123onetwothree Yes it will work. The thing that won't work is how I created the anonymous class in $run[0]
and if i have an array with parameters how can i pass that array to the function ? can i use call_user_func_array() ?
@SagarGuhe What do you mean this might not work in PHP7 ? The only version in which above code will work is PHP 7.
@123onetwothree I would use the splat operator.
splat operator ? how
|

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.