tags:

views:

354

answers:

3

I'm using a templating engine that inserts code in my site where I want it.

I wrote a function to test for something which is quite easy:

myfunction() { return '($this->data["a"]["b"] ? true : false)'; }

The problem is, $this->data is private, and I can't access it everywhere, so I have to use getData(); which causes my problem.

$this->getData()['a']['b']

does not work (obviously), and assigning the value first doesn't either because it will be used directly in an if() block.

Any ideas?

+1  A: 

Hi,

You cannot use something like this :

$this->getData()['a']['b']

ie, array-access syntax is not possible directly on a function-call.

Youy have to use some temporary variable, like this :

$tmp = $this->getData();
$tmp['a']['b']    // use $tmp, now

In your case, this probably means using something like this :

function myfunction() {
  $tmp = $this->getData();
  return ($tmp['a']['b'] ? true : false);
}

You have to :

  • first, call your getData() method, and store its return value in a temporary varibale
  • then, use that temporary variable for your test

You don't have much choice about that, actually...

Pascal MARTIN
Well, as I said, my problem is that this code gets inserted, directly in if(/* code goes here */) so defining a function there is not really possible...
enyo
Can you not assign the result of the method call to a variable before the if statement, and use that variable in the if statement, instead of directly trying to call the method from the if statement ?
Pascal MARTIN
Unfortunately no... This is a templating engine, and I have no control over it.
enyo
A: 

$this->data is always accessible, if it is protected. $object->data is not accessible from everywhere, so if you're returning $this in your code, and it is evaluated as such, it should be ok.

Btw, there is a bug in your code: The quotes need to be escaped.

myfunction() { return '($this->data[\'a\'][\'b\'] ? true : false)'; }
soulmerge
Yeah sorry... I corrected my post: $this->data is private of course.Also corrected my typo when creating the bug.
enyo
A: 

Ok... apparently there really isn't a better way, so I'm going to answer myself with a not so beautiful solution:

I created the function:

arrayGet($array, $index) { return $array[$index]; }

And used it like this:

myfunction() { return '(arrayGet(arrayGet($this, "a"), "b") ? true : false)' }

This is not pretty but works.

enyo