0

is it possible to do something like this in php?

$this->getUser$number();

I can't find if there's somekinda syntax to make this possible.

Regards

Adrian B
  • 1,490
  • 1
  • 19
  • 31
  • Yes, inside a class. http://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php – putvande Jun 21 '14 at 18:48

5 Answers5

1

Yes, there is:

$this->{"getUser".$number}();

Of course you can use the same syntax outside a method:

$obj = new Something();
$obj->{"getUser".$number}();

That said, code like this is a bad smell and should be avoided. For example, it's better to make the getUser method accept an argument and call it like this:

$this->getUser($number);

This way the call site remains "sane", while the implementation of getUser can use $number as e.g. an index into an array and also achieve much better clarity.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

It's called OOP programming, it is used in most likely any big system. It is also used alot in a MVC application. Read more about OOP programming here; http://www.php.net//manual/en/language.oop5.php

These expression can also be used like this;

$this->$name

or even further to;

$this->name =& $name
$this->name = $${val}
Tosfera
  • 512
  • 3
  • 14
0

It is not possible to use symbol $ as name of function. But on the other hand $this->getUserNumber(); you can use inside some class.

Facedown
  • 192
  • 1
  • 2
  • 10
0

You can also do this as

$number = "10";
$func = "getUser".$number ;
$this->$func();

it'll call some function named

getUser10();

DWX
  • 2,282
  • 1
  • 14
  • 15
-1

Yes you can do this:

   $methodName = 'getUser' . $number;
   $this->$methodName();
Adrian B
  • 1,490
  • 1
  • 19
  • 31