Bas
Bas

Reputation: 2400

PHP foreach array with function names and dynamically execute them

I want to call the function xxx() and execute getCdl(). In getCdl() function i want to call the method dynamically. But this gives an error Call to undefined function trader_​cdl2crows. But when i execute trader_​cdl2crows() directly it works.

How can achieve this? :)

Functions:

public function xxx(){
$cdls = [
    'trader_​cdl2crows',
    'trader_​cdl3blackcrows',
    'trader_​cdl3inside',
    'trader_​cdl3linestrike',
    etc,etc,etc
$result = [];
foreach ($cdls as $cdl) {
    $result[$cdl] = $this->getCdl($cdl,$ticksPerType);
}
vardump($result);
}

private function getCdl($method,$ticksPerType){
return $method(
    $ticksPerType[$this->ticks::TICK_TYPE_OPEN],
    $ticksPerType[$this->ticks::TICK_TYPE_HIGH],
    $ticksPerType[$this->ticks::TICK_TYPE_LOW],
    $ticksPerType[$this->ticks::TICK_TYPE_CLOSE]
);
}

Upvotes: 0

Views: 101

Answers (1)

Jeto
Jeto

Reputation: 14927

Your function names, such as trader_​cdl2crows, have an zero-width space character right after the _ character.

Try encoding it using this tool for instance and it will give you: trader_​cdl2crows for the first function (​ is that zero-width char), and similar results for the rest of them. You can also notice by attempting to use arrow keys while editing these names within any input field/text editor such as a SO comment (need two "steps" to go from _ to c and vice-versa).

So replace your array with this:

$cdls = [
  'trader_cdl2crows',
  'trader_cdl3blackcrows',
  'trader_cdl3inside',
  'trader_cdl3linestrike',
  // if you have more function names, rewrite them here
];

This looks the exact same but does not have the invisible characters in it.

Upvotes: 2

Related Questions