Created
January 14, 2019 20:09
-
-
Save heiglandreas/39560248c77830f8150c691086dfb0ee to your computer and use it in GitHub Desktop.
Different Scopes for reading and writing properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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