0

I can't seem to find an answer to this albeit I am probably not looking for the right thing being new to classes and oop. I would like to know if you can use a variable when calling a class method.

When a user logs into my system I wish to display them some chart on a dashboard based on their user role.

For starters here is an example of my class

class Dashboard
{
  function get_guest_graph1()
  {
    return 'guest graph';
  }

  function get_user_graph1()
  {
    return 'user graph';
  }
}

On the page I can echo say

$user->userRole;

This will return either guest or user.

So once I have established the role and put this into a varible ie

$role

Is there a way I can then do the following?

Dashboard::get_$role_graph1();
1

2 Answers 2

1

While this question was already answered, I think there are far better ways to handle this, if readability is in question.

For starters, use camel casing on functions rather than chaining_characters_for_variable_names.

class Dashboard {
    function getFirstUserGraph() {
        return 'user graph 1';
    }
}

I would discourage using numbers in a function name!

Secondly, to accomplish your desire of calling Dashboard::getFirstUserGraph() simply make that a static function:

public static function getFirstUserGraph() {}

Then you don't have to instantiate the class but use it statically.

Lastly, to call a class method via a variable is rather simple without the ugliness of call_user_func(). See below:

$getGraph = "getFirstUserGraph";
Dashboard::$getGraph();

Works like a champ and looks a lot nicer. Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you can, but use with caution:

call_user_func(array("Dashboard", "get_" . $role . "_graph1"), $args);

3 Comments

can I ask why use with caution is this a bad thing to do? Thank you for your quick response, will mark as correct answer but have to wait 8 minutes.
There potential for abuse here. call_user_func may make your code unreadable. If your code is more like: if ($bool) { op1(); } else { op2(); } (ie. you know all the possibilities) just write it like that, don't use call_user_func.
Thank you for all your help. I will eventually have 7 user types, but I agree. The easier to read, the easier to succeed.

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.