Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Last active April 22, 2016 08:28
Show Gist options
  • Save geerteltink/b94f56ddef6b16dd9e19ac71d791b66b to your computer and use it in GitHub Desktop.
Save geerteltink/b94f56ddef6b16dd9e19ac71d791b66b to your computer and use it in GitHub Desktop.
PHP set private properties without setters statically
<?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