Skip to content

Instantly share code, notes, and snippets.

@heiglandreas
Created January 14, 2019 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiglandreas/39560248c77830f8150c691086dfb0ee to your computer and use it in GitHub Desktop.
Save heiglandreas/39560248c77830f8150c691086dfb0ee to your computer and use it in GitHub Desktop.
Different Scopes for reading and writing properties
<?php
class Foo
{
// when there are two visibility declarations following one another
// the first one describes reading, the second one writing.
// If it's only one declaration it is used for reading *and* writing
// So this can be read publicly but only this class can write to the property.
public private int $int;
public function __construct(int $int)
{
$this->int = $int;
}
}
$foo = new Foo(12);
echo $foo->int // 12
$foo->int = 13 // Fatal Error or Exception
<?php
class Bar
{
private public int $int;
public function setValue(int $int) : void
{
$this->int = $int;
}
public function getValue() : int
{
return $this->int;
}
}
$bar = new Bar();
$bar->setValue(13);
$bar->getValue(); // 12
$bar->int = 12;
echo $bar->int // Fatal Error or Exception as reading is only possible from within the instance
echo $bar->getValue() // 12
// Should it be possible to allow reading or writing only from the outside but *not* from the inside?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment