Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Tutorial {
- /**
- * Variables inside a class are accessed by referencing the class and the variable.
- * Example: $this->publicString, $this->protectedString, $this->privateString
- */
- public $publicString = 'Anything can access this!';
- protected $protectedString = 'This can be accessed by sub-classes!';
- private $privateString = 'This can't be accessed from anywhere else!';
- /**
- * If a constuctor takes arguments, they are given at initialization.
- * Example: $tutorial = new Tutorial($arguments);
- * Note: There are some interestingly fancy ways to handle args in constructors.
- */
- public function __construct() {
- print('This code executes when you initialize or "construct" the class.');
- $this->publicScope();
- $this->protectedScope();
- $this->privateScope();
- }
- // Full External Accessibility
- public function publicScope()
- {
- print('This function can be accessed anywhere.');
- }
- // Partial External Accessibility
- protected function protectedScope()
- {
- print('This function can only be accessed from within the class, or subclasses.');
- }
- // No External Accessibility
- private function privateScope()
- {
- print('This function can only be accessed from within the class.');
- }
- }
- /**
- * If a class extends another class, it has access to all the functions in the parent class.
- * And it can alter the functions from the parent class.
- */
- class ExtendedTutorial extends Tutorial
- {
- public function __construct($someData)
- {
- /**
- * Using the 'parent::' prefix directly references parent values.
- * It's generally used to have two functions with the same name accessible in the same scope.
- */
- parent::__construct();
- print($someData);
- }
- public function publicScope()
- {
- print($this->publicString);
- }
- protected function protectedScope()
- {
- print($this->protectedString);
- }
- private function privateScope()
- {
- print($this->privateString);
- }
- }
- /**
- * Initializes the Tutorial Class to the variable $tut.
- * Since all the functions in the Tutorial Class are executed in the constructor they will run immediately.
- */
- $tut = new Tutorial();
- //$tut->publicScope(); # Success
- //$tut->privateScope(); # Failure, Can only be called within the class or subclasses.
- //$tut->protectedScope(); # Failure, Can only be called within the class.
- /**
- * Yay Subclass initialization.
- * This can access all the public and protected members of the parent class.
- */
- $extTut = new ExtendedTutorial("This is going to print after the parent constructor executes.");
- # Reference Initialized Variable, Call publicScope(); function
- $extTut->publicScope();
- # Will Fail
- #$extTut->protectedScope();
- #$extTut->privateScope();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement