Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

__get() and what context it is invoked in

$
0
0
Is there any way to determine what context a __get() is invoked in? I'm thinking in terms of templating engines, specifically a javascript template and displaying boolean values as strings. Take the following for example:
<? if($this->isViewable): ?>
$true = <?= $this->isViewable ?>;
<? else: ?>
$false = <?= $this->isViewable ?>;
<? endif; ?>


If there is no __get() method for $this, the output of the above code will either be '$true = 1;' OR '$false = ;' depending on the value of $this->isViewable.

On the other hand, if we define the __get() method as:
public function __get($property)
{
  if($this->$property === false) return 'false';
  if($this->$property === true) return 'true';
  return $this->$property;
}


...then the conditional statement in the template will always be true, so the output will either be '$true = true;' or '$true = false;'. Anyone got any ideas about how to tackle this by using __get()? I've racked my brain and I'm not sure it's possible. The two options I can see are:
  • Have two properties ($isViewable and $stringIsViewable) and store both the boolean and string values separately. This seems messy to me, as it could lead to mismatches between the intended data.
  • Use a custom PHP function in the template which casts booleans, nulls, etc to string, like so: <?= toString($this->isViewable) ?>

I prefer the second option, but I'd like some feedback/insight from forum colleagues :)/>

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>