From cd6ae7f26198d463a881c9a99012dc06cf9502cd Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 25 Jul 2015 14:03:38 -0400 Subject: [PATCH] Creating pets with static method --- c&s20150725/inheritance.php | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/c&s20150725/inheritance.php b/c&s20150725/inheritance.php index dcbf31a..9357c9a 100644 --- a/c&s20150725/inheritance.php +++ b/c&s20150725/inheritance.php @@ -4,6 +4,16 @@ class Pet { public $name; public $isRunning = false; + private function __construct() + {} + + public static function create($name) + { + $newPet = new static; + $newPet->name = $name; + return $newPet; + } + public function run() { $this->isRunning = true; @@ -24,8 +34,7 @@ class Dog extends Pet { } } -$cat = new Pet(); -$cat->name = 'Felix'; +$cat = Pet::create('Felix'); var_dump($cat); @@ -33,8 +42,7 @@ $cat->run(); var_dump($cat); -$dog = new Dog(); -$dog->name = 'Fido'; +$dog = Dog::create('Fido'); var_dump($dog);