The Humble Rat
The Humble Rat

Reputation: 4696

Use variable when calling class method

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();

Upvotes: 0

Views: 82

Answers (2)

Rottingham
Rottingham

Reputation: 2604

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!

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

Yes, you can, but use with caution:

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

Upvotes: 0

Related Questions