Last active
April 22, 2016 08:28
-
-
Save geerteltink/b94f56ddef6b16dd9e19ac71d791b66b to your computer and use it in GitHub Desktop.
PHP set private properties without setters statically
This file contains hidden or 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 User | |
{ | |
private $name; | |
public function __construct() | |
{ | |
} | |
public static function register(string $name) | |
{ | |
// Create a new class | |
$user = new self(); | |
// Set private property ??? | |
$user->name = $name; | |
// Return class | |
return $user; | |
} | |
public function getName() | |
{ | |
return $this->name; | |
} | |
} | |
// Works ??? | |
$user = User::register('username'); | |
var_dump($user->getName()); // username | |
// Not working as expected | |
$user = new User(); | |
$user->name = 'username'; // Error: Cannot access private property User::$name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment