Beruflich Dokumente
Kultur Dokumente
class Something {
// In OOP classes are usually named starting
with a cap letter.
var $x;
function setX($v) {
// Methods start in lowercase then use
lowercase to separate
// words in the method name example
getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
Object Oriented Programming in PHP - Data Members
and Functions
• Data members are defined in PHP using a "var" declaration inside the class
and they have no type until they are assigned a value.
• A data member might be an integer, an array, an associative array or even
an object.
• Methods are defined as functions inside the class, to access data members
inside the methods you have to use $this->name, otherwise the variable is
local to the method.
• You create an object using the new operator:
$obj=new Something;
Then you can use member functions like:
$obj->setX(5);
$see=$obj->getX();
• The setX member function assigns 5 to the x data member in the object obj (not in the class),
then getX returns its value; 5 in this case.
• You can access the data members from the object reference using for example: $obj->x=6.
However, this is not a very good OOP practice.
• I encourage you to set data members by defining methods to set them and access the data
members by using retrieving methods.
•
Inheritance
Inheritance is easy in PHP using the extends keyword:
<?php
class Another extends Something {
var $y;
function setY($v) {
// Methods start in lowercase then use uppercase initials to
// separate words in the method name example getValueOfArea()
this->y=$v;
}
function getY() {
return $this->y;
}
}
?>
Object Oriented Programming in PHP - Constructors
Then: