Radical_Activity
Radical_Activity

Reputation: 2738

How to get an Object's Object in PHP

I'm having some troubles with some object oriented programming in PHP.

I basically have a function within a class, which displays some text:

  public function text() {
       echo 'text';
    }

Now I want to store the function name in an arra,y so I can reference it later:

$functions = array('text_func' => 'text');

And in an other function I want to call the above function with the Array reference, so I did the following:

public function display() {
   $this->functions['text_func']();
}

The result will be basically:

text();

My question is that, how is it possible to make this function run? (The correct way it should be look like: $this->text()). However I can't do something like this, because it gives me an error:

$this->$this->functions['text_func']();

Any idea or solution for my problem?

Upvotes: 0

Views: 68

Answers (4)

Álvaro González
Álvaro González

Reputation: 146660

The error message you carefully ignore probably warns you that $this cannot be converted to string. That gives you a pretty good clue of what's going on.

(Long answer is that method names are strings. Since PHP is loosely typed, when it needs a string it'll try to convert whatever you feed it with into string. Your class lacks a __toString() method, thus the error.)

You probably want this:

$this->{$this->functions['text_func']}();
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Upvotes: 1

cardeol
cardeol

Reputation: 2238

$this does not contain a reference for itself, so you should try just

$this->display();

instead of

$this->$this->functions['text_func']();  // WRONG

Upvotes: 0

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

You're confusing a lot of things. First of all, you can use the magic constants __METHOD__ and __CLASS__ to determine in which class type and method you are currently executing code.

Secondly, a callable in PHP is defined as either an array with an object instance or static class reference at index 0, and the method name at index 1, or since PHP 5.2 a fully qualified string such as MyClass::myFunction. You can only dynamically invoke functions stored as one of these types. You can use the type hint callable when passing them between functions.

Upvotes: 0

Dan Walker
Dan Walker

Reputation: 474

Here's an example from PHP.net that should help:

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

Source: http://www.php.net/manual/en/functions.variable-functions.php

Upvotes: 0

Related Questions