Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Overriding Parent Methods
- //Nice work!
- //Sometimes we want a child class (or subclass)
- to be able to override a property or method of its parent
- class (or superclass).
- <html>
- <head>
- <title>Override!</title>
- </head>
- <body>
- <p>
- <?php
- class Vehicle {
- public function honk() {
- return "HONK HONK!";
- }
- }
- class Bicycle extends Vehicle{
- public function honk() {
- return "Beep beep!";
- }
- }
- $bicycle = new Bicycle();
- echo $bicycle -> honk();
- // Add your code below!
- ?>
- </p>
- </body>
- </html>
- //Class Constants and Scope Resolution
- //We've talked a lot about changing variables in PHP,
- but sometimes we want variables that don't change.
- These are prefixed with the const keyword (short for constant).
- //PHP lets us set constants on a class-by-class basis!
- Each class has its own scope, which is the context in which
- its variables can be used.
- <html>
- <head>
- <title>Scope it Out!</title>
- </head>
- <body>
- <p>
- <?php
- class Person {
- }
- class Ninja extends Person {
- // Add your code here...
- const stealth = "MAXIMUM";
- }
- echo Ninja::stealth;// ...and here!
- ?>
- </p>
- </body>
- </html>
- The Static Keyword
- Nice work!
- You probably noticed that we could access the Ninja class constant
- without actually creating an instance of Ninja,
- and if you're particularly precocious,
- you might be wondering whether it's possible to access class
- properties or methods without creating an instance of the class.
- The answer: yes!
- The static keyword lets you use a class' property or
- method without having to create an instance of that class.
- It works like this:
- class Person {
- public static $isAlive = "Yep!"
- public static function greet() {
- echo "Hello there!";
- }
- }
- echo Person::$isAlive;
- // prints "Yep!"
- Person::greet();
- // prints "Hello there!"
- When combined with the scope resolution operator, this lets us access class information without having to instantiate anything. Neat, right?
- <html>
- <head>
- <title></title>
- </head>
- <body>
- <p>
- <?php
- class King {
- // Modify the code on line 10...
- public static function proclaim() {
- echo "A kingly proclamation!";
- }
- }
- // ...and call the method below!
- King::proclaim();
- ?>
- </p>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement