#native_company# #native_desc#
#native_cta#

Object Oriented Programming in PHP: The Way to Large PHP Projects Page 2

By Luis Argerich
on January 25, 2008

Data members are defined in php using a “var” declaration inside the class, data members
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 by:
$obj->setX(5);
$see=$obj->getX();
The setX member function assigns 5 to the x datamember in the object obj (not in the class),
then getX returns its value: 5 in this case.
You can access the datamembers from the object reference using for example: $obj->x=6; however,
this is not a very good OOP practice. I enforce you to set datamembers by defining methods to
set them and access the datamembers by using retrieving methods. You’ll be a good OOP programmer
if you consider data members inaccesible 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 extend keyword.

<?php

class Another extends Something {

    var 
$y;

    function 
setY($v) {

        
// Methods start in lowercase then use lowercase to seperate

        // words in the method name example getValueOfArea()

        
$this->y=$v;

    }

    function getY() {

        return 
$this->y;

    }

}

?>



1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Luis Argerich

Comment:



Comment: