php classes and objects

One of the great features in php is the Object-oriented programming, using objects in php and other programming language is to simplify the code and to increase the control and manipulating of the data and functions, start using classes in php is very simple.

The next example illustrate how to create and use a simple class.
1
2
3
4
5
6
7
8
9
<?php
 
class student {
    /* class variables and functions */
}
 
 $a = new student;
 $b = new student;
?>


Adding variables
simply insert all variables of any type after define a class name, you can deal with any variable in the class using $this->variable_name
1
2
3
4
5
6
7
8
9
<?php
 
class student {
    var $Fname;
    var $Lname;
    var $address;
    var $registration_date;
    var $marks;


Creating a class instance .
When we create a new class object it automatically call a __construct() function, so we can use this function to set some initial values by passing arguments to this function.
In the following example I make construct function with three argument and set the last one as an optional argument.
10
11
12
13
14
15
16
17
function __construct($n1, $n2, $adr="test city ,test street."){
    $this->Fname = $n1;
    $this->Lname = $n2;
    $this->address = $adr;
    $this->registration_date = date("Y/n/j");
    }
}


Adding functions to class:
To control the class objects and to simply work with its variable we use functions related to the same class, for example we can pass several arguments by function and then we can get a result of any mathematical process by return function value.
18
19
20
21
22
23
24
25
26
27
28

function add_marks($m){
    $this->marks[ count($this->marks)] = $m;
    }
 
function mark_avg(){
    for ($i=0; $i<count($this->marks); $i++)
        $total = $total + $this->marks[$i];
    return ($total  / count($this->marks));
    }


How to call a class.
you only need to identify a new variable as a new student class passing the values needed to set when creating the object, $n1 and $n2 variables are required, the third argument $adris set to be an optional, when you ignore it the default value in the construct will be taken to the third argument.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
    $a = new student("John","Anderson");
    echo "Student name : $a->Fname  $a->Lname"."<br>";
    echo "Student address : $a->address"."<br>";
    echo "Student registration_date : $a->registration_date"."<br><br>";
    
    $a->add_marks(85);
    $a->add_marks(87);
    $a->add_marks(82);
 
    echo "All Student marks in array : ";
    print_r($a->marks);
    
    echo "<br>";
    echo "Student average marks : ".$a->mark_avg();
?>


If this post was good and helpful for you, Please give it Like.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment