geirby

php8_init_with_class_obj

Mar 30th, 2022 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.71 KB | None | 0 0
  1. class User
  2. {
  3.     public function __construct(
  4.         private int $id = 0,
  5.         private string $name = ''
  6.     )
  7.     {
  8.     }
  9.  
  10.     public static function getInstance($id, $name) : self
  11.     {
  12.         return new self($id, $name);
  13.     }
  14.     public function getUserName() : string
  15.     {
  16.         return $this->name;
  17.     }
  18. }
  19.  
  20. class SomeClass
  21. {
  22.     private User $user;
  23.     public function __construct(
  24.         private User $user = User::getInstance($id, $name)
  25.     )
  26.     {
  27.         //$this->user = $user::getInstance()
  28.     }
  29.     public function getUserName(): string
  30.     {
  31.         return $this->user->getUserName();
  32.     }
  33. }
  34. $user = new User(1, 'John');
  35. $cls = new SomeClass($user);
  36. echo $cls->getId();
Add Comment
Please, Sign In to add comment