Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts

Friday 1 November 2013

OOP Series : Inheritance

One of OOP's strengths is that it provides the concept of inheritance. This becomes particularly useful when developers are working together and extending classes. In this first example I'm not going to focus on controlling the visibility of properties and methods. Everything will be public. Visibility will be covered in another blog entry.
PHP:car.class.php
<?php
class car
{
public $mypublicvariable;
function __construct()
{
$this->mypublicvariable = 'guitar';
}
function changevalue()
{
$this->mypublicvariable = 'beer';
}
}
?>
PHP:extendedcar.class.php
<?php
require_once 'car.class.php';
class extendedcar extends car
{
function __construct()
{
parent::__construct();
}
function changevalue()
{
$this->mypublicvariable = 'chocolate';
}
}
?>
JavaScript:car.class.js
car = function()
{
this.mypublicvariable = 'guitar';
}
car.prototype.changevalue = function()
{
this.mypublicvariable = 'beer';
}
JavaScript:extendedcar.class.js
extendedcar = function()
{
car.call(this);
}
extendedcar.prototype = new car();
extendedcar.prototype.constructor = car;
extendedcar.prototype.changevalue = function()
{
this.mypublicvariable = 'chocolate';
}
Now a file (index.php) which creates an object from both.
<?php
require_once 'car.class.php';
require_once 'extendedcar.class.php';
$mycar = new car;
$myextendedcar = new extendedcar;
echo $mycar->mypublicvariable.'<br />';
$mycar->changevalue();
echo $mycar->mypublicvariable.'<br />';
echo $myextendedcar->mypublicvariable.'<br />';
$myextendedcar->changevalue();
echo $myextendedcar->mypublicvariable.'<br />';
?>
<script src="car.class.js"></script>
<script src="extendedcar.class.js"></script>
<script>
var mycar = new car();
var myextendedcar = new extendedcar();
document.write(mycar.mypublicvariable+'<br />');
mycar.changevalue();
document.write(mycar.mypublicvariable+'<br />');
document.write(myextendedcar.mypublicvariable+'<br />');
myextendedcar.changevalue();
document.write(myextendedcar.mypublicvariable+'<br />');
</script>

Monday 5 March 2012

Multiple inheritance through PHP using traits

I actually took this code from http://php.net. Multiple inheritance has always been a bit dodgy for me in PHP. This is an excellent example of how to use traits to achieve it.

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo ' World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();>
?>