0

here's my code:

$menu .= $this->$item['type']($item);

$item['type'] is a string - 'single' and it uses method single(). Yet the browser shows me this error:

Array to string conversion

I have no idea why, since single returns a string, $item['type'] also is a string. I even tried checking this:

var_dump($this->$item['type']([]));

and it still returns the same error. Do you know why?

5
  • Have you tried (string)($this->$item['type']($item)); Commented Jul 4, 2017 at 22:44
  • did you try to see var_dump($this->$item['type']); it returns what ? Commented Jul 4, 2017 at 22:46
  • seifeddine Besbes - it's the same error Commented Jul 4, 2017 at 22:49
  • there is one explanation that $item['type'] is an array, perhaps an array contains your string try to see what $item['type'] returns to know for sure Commented Jul 4, 2017 at 22:55
  • that's the problem, I've tried multiple times and it always returns string(6) "single" Commented Jul 4, 2017 at 22:57

2 Answers 2

1

You need to wrap the string that was found in the array element in curly brackets before using it as a method name to your object:

$menu .= $this->{$item['type']}($item);

See here: http://php.net/manual/en/language.types.object.php

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

2 Comments

I'm just curious - did it suppose to work in ealier versions of PHP? I have project that was running php 5.6 and I was working on 7.0 when it stopped working.
Well, honestly, I don't know. But looking at it again, I can understand, why the brackets are needed here. Without them PHP (any version!) would have to "think" that you want to access the function under the $type-th element of the object property $this->$time (assuming $time to be a string!). The curly brackets force PHP to evaluate the term$time[$type] first.
1

i believe this will work try it :

$method = $item['type'];
var_dump($this->$method($item));

2 Comments

it does and I have no idea why. Care to explain?
yes sure, as we know php support variable functions but only simple variable. it does not support array as variable function. php.net/manual/en/functions.variable-functions.php

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.