PHP Classes Example
In this article, we will see what is php classes example. PHP provides extensive support for developing object-oriented web applications. An object is a self-contained piece of functionality that can be easily used and reused as the building blocks for a software application. Object consists of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.
The syntax for Defining Classes
<?php
class phpclass (NOTE : No $ before class name)
{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2)
{
}
}
?>
where,
- The special form class is followed by the name of the class that we want to define.
- A set of braces enclosing any number of variable declarations and function definitions.
- Variable declarations start with the special from var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
- Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.
Ex:
<?php
class Books{
/* Member Variables */
var $price = 100;
/* Member functions*/
function display(){
echo "Price = " . $this->price;
} }
$physics = new Books;
$physics->display();
?>
Here, the variable $this keyword is a special variable and it refers to the same object. To display the class function, we need to create a PHP object as in the above code.
Output: