Php class data members

PHP tips & tutorial for Beginners

Object Oriented Programming with PHP 5 More OOP

Object Oriented Programming in PHP – 2

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.

You’ll be a good OOP programmer if you consider data members inaccessible and only use methods from the object handler. Unfortunately PHP doesn’t have a way to declare a data member private so bad code is allowed.

Inheritance is easy in PHP using the extends keyword:

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;
>

Objects of the class “Another” now have all the data members and methods of the parent class (Something) plus its own data members and methods.

$obj2=new Something;
$obj2->setX(6);
$obj2->setY(7);

Multiple-inheritance is not supported so you can’t make a class extend two or more different classes.

You can override a method in the derived class by redefining it. If we redefine getX in “Another” we can no longer access method getX in “Something”.

If you declare a data member in a derived class with the same name as a data member in a Base class the derived data member “hides” the base class data member when you access it.

Источник

Читайте также:  Building web applications with python
Оцените статью