0

When I say a variable i don't really mean a constant.

What i don't mean :

class foo {
  const BAR = ($_ENV === 'dev') ? 'pages' : 'prod-pages'; // this will fails anyways

  public function randomFct () {
    echo "BAR"; // of course we can't process a constant in a string
  }
}

What i mean :

class foo {
  private $BAR;

  public function __construct () {
    $this->BAR = ($_ENV === 'dev') ? 'pages' : 'prod-pages';
    $this->BAR = 'new'; // throws an error
  }

  public function randomFct () {
    echo "{$this->BAR}";
  }
}

edit : I use php7.1

vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • however: why exactly do you nead a read-only variable? it's private, so it can't be accessed from anything but the actual class you are writing - so: just don't write to it. and if you *do* need to access it from somewhere else, the "clean" way would be a `$foo->getBar();` anyway. – Franz Gleichmann Jan 23 '17 at 18:46
  • Nope. It is not: There is an old PHP RFC called [Readonly Properties](https://wiki.php.net/rfc/readonly_properties) – felipsmartins Jan 23 '17 at 18:49
  • @FranzGleichmann because i have a class with a lot of path manipulation, and I wanted to be able to write strings like `{$this->base}/{$this->relpath}/{$this->filename}`. Also the possible duplicate is not really appropriate because `__set` will not work inside the class, I believe `__set` only get called when you try to access a class' variable outside of the class. – vdegenne Jan 23 '17 at 19:14
  • @felipsmartins since it is withdrawn, one could argue about it. but SO is not the place for arguing. also, again: from inside the class you can still use `$this->bar`, and since you write the class you can just *not write to the variable*, while making it read-only accessible with a public function getBar. – Franz Gleichmann Jan 23 '17 at 19:21
  • @FranzGleichmann yeah ok that's very true, now I understand – vdegenne Jan 23 '17 at 19:26

0 Answers0