diff --git a/assets/templates/_table_of_contents.phtml b/assets/templates/_table_of_contents.phtml index c6d9ad9..a0e2e0c 100644 --- a/assets/templates/_table_of_contents.phtml +++ b/assets/templates/_table_of_contents.phtml @@ -15,6 +15,7 @@
  • Classes: Inheritance
  • Classes: Visibility
  • Classes: Constructor
  • +
  • Static
  • Credits diff --git a/code/static.php b/code/static.php new file mode 100644 index 0000000..1050bcc --- /dev/null +++ b/code/static.php @@ -0,0 +1,70 @@ +color = $color; + } +} + +// Like building a house, a class is a blueprint that +// defines what the house can do and the object is the house itself that can actually +// perform the actions defined in the blueprint. +$house = new House('Green'); + +// However, what if you want the blueprint to have properties and methods? +// That is when you use the "static" keyword. In this class, we will define a default color +// on the class itself and then use it when creating a new object. +class Skyscraper +{ + private static $popularColor; + public $color; + + public static function setDefaultColor($color) + { + self::$popularColor = $color; + } + + public function __construct() + { + $this->color = self::$popularColor; + } +} + +// You can access static methods and properties using double colons on "self" inside the object +// or on the class name outside of the object. Static methods and properties can only access +// other static methods and properties. +Skyscraper::setDefaultColor('Grey'); +$skyscraper = new Skyscraper(); +echo $skyscraper->color . "\n"; + +// Often, you will see static constructors in PHP. +// A static constructor creates a new instance of an object. Why would do that when you just use "new Class" to create +// a new object? The most common reason is to make the code more readable. +class TinyHouse +{ + private $color; + private $wheels; + private $trailer; + + public static function build($color, $wheels, $trailer) + { + return new self($color, $wheels, $trailer); + } + + public function __construct($color, $wheels, $trailer) + { + $this->color = $color; + $this->wheels = $wheels; + $this->trailer = $trailer; + } +} + +// Using "build" can make more sense than "new", but it is ultimately a personal choice. +$house = TinyHouse::build('Blue', 4, true); diff --git a/config.php b/config.php index e584669..f4359eb 100644 --- a/config.php +++ b/config.php @@ -87,6 +87,12 @@ return [ 'title' => 'Classes: Constructor', 'subtitle' => 'Construct your objects', 'previous' => 'classes-visibility', + 'next' => 'static', + ]), + Page::create('static', null, 'static.php', [ + 'title' => 'Static', + 'subtitle' => 'Adding properties and functions to the blueprint', + 'previous' => 'classes-constructor', 'next' => '', ]), ],