1

I want to invoke a function on an object. The name of the function is stored in a static property of a class (of which the object is an instance). This invocation happens inside one of the object's methods.

None of the approaches below work (it's after the getBean()-> that I'm confused).

$this->getBean()->User::$BEANSCHEMA_FIRST_NAME;

$this->getBean()->self::$BEANSCHEMA_FIRST_NAME;

$this->getBean()->$self::$BEANSCHEMA_FIRST_NAME;

How can I accomplish this, preferrably without a weird library function like call_user_func()?

hakre
  • 193,403
  • 52
  • 435
  • 836
cheeken
  • 33,663
  • 4
  • 35
  • 42

1 Answers1

1

Use {}, hope this helps (Demo):

class Funcaro
{
    public static $MUNKI_SELF = 'munki';
    public function munki()
    {
        echo 'You got me :)', "\n";
    }
}

class Callara extends Funcaro
{

    public function get()
    {
        return new Funcaro();
    }
    public function call()
    {
        $this->get()->{self::$MUNKI_SELF}();
    }
}

$c = new Callara();

$c->get()->munki();

$munki = 'munki';

$c->get()->$munki();

$c->get()->{Funcaro::$MUNKI_SELF}();

$c->call();

Related: PHP curly brace syntax for member variable

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Darn it, I only tried parentheses. Should have thought to try curlies. Thanks! – cheeken Jul 29 '11 at 01:26
  • @cheeken: You're welcome. A simple example always helps as well :) - the curly brackets can be used to signal PHP which part of the expression you want to use as the function label. Works for variable names and property names as well. – hakre Jul 29 '11 at 01:28
  • @hakre: This is a pretty good example, but I don't get why the Callara class has a get() method that is esentially a factory for insantiating and return `Funcaro` objects, which is the parent of the very same class. This seems counter-intuitive to me because we already have an object with access to parent attributes, so you could simply make a call like: `$c->{Funcaro::$MUNKI_SELF}();` – Mike Purcell Jan 21 '12 at 22:07
  • @MikePurcell: Technically, it's not necessary to call a function, but if you look at the question, I think I wrote that because it's more close to the scenario given in the question (`getBean()`). – hakre Jan 22 '12 at 08:37
  • Understood. Always multiple ways to skin a cat. +1 for good example. – Mike Purcell Jan 22 '12 at 18:11