0

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?

1
  • you should call $this->display(); Commented Jan 20, 2014 at 17:44

4 Answers 4

1

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']}(); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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

$this->display(); 

instead of

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.