Showing posts with label properties. Show all posts
Showing posts with label properties. Show all posts

Monday 21 October 2013

OOP Series : Properties and methods

Why? I don't know, but the creators of OOP decided to rename variables and functions as properties and methods respectively. The crazy thing is, that in the code, you will see references to things like 'var' and 'function'. Hey ho! Here are 2 simple examples of how they are declared and used in my example of the desk lamp which lights up my keyboard on this dull day.
PHP : desklamp.class.php
<?php
class desklamp
{
public $power = 'OFF';
function onoffswitch()
{
$this->power = $this->power == 'OFF' ? 'ON' : 'OFF';
}
}
?>
JavaScript : desklamp.class.js
desklamp = function()
{
this.power = 'OFF';

this.onoffswitch = function()
{
this.power = this.power == 'OFF' ? 'ON' : 'OFF';
};
};
Now a file (index.php) which creates objects from both and makes the switch.
<?php
require_once 'desklamp.class.php';
$mydesklamp = new desklamp;
echo 'PHP desk lamp power = '.$mydesklamp->power.'<br />';
$mydesklamp->onoffswitch();
echo 'PHP desk lamp power = '.$mydesklamp->power.'<br />';
?>

<script src="desklamp.class.js"></script>
<script>
var mydesklamp = new desklamp;
document.write('JS desk lamp power = '+mydesklamp.power+'<br />');
mydesklamp.onoffswitch();
document.write('JS desk lamp power = '+mydesklamp.power);
</script>