PHP Class & Objects


Objects and classes are used to specify an object and combine data representation and methods for manipulating the data. The members of the class are also known as data and functions within the class.

PHP Class and Object

Class

The class is a blueprint of an object. Collection of objects is known as class. It is a logical entity. It starts with the keyword followed by the class name and the class body.

Syntax:

 class class_name
{
	variable;
	type method_name(parameter_list);
}

Object

The object in PHP language matches a real-world entity. Objects having state and behavior. In PHP language class provide the blueprint of an object, so basically, an object is created from a class.

The new operator is used to create a heap memory space for the class object.

Syntax:

objectname= new class_name(); 
PHP object

Defining the Object of a Class

An object is an instance of a class. A class must be defined pior to the object declaration. A class provides a template, which defines the methods and variables that are required for objects of the class type.

Syntax:

class class_name
{
	 variable;
	type method_name(parameter_list);
}
object= new class_name(); 

Access Specifiers

Specifier Inside Class Subclass Outside Class
public
protected
private

Accessing Class Members

The data members or methods of a class construct is accessed using the . operator.


Example 1:

<?php
class Rectangle {
    public $length;
    public $breadth;
    public $area;
}

$r1 = new Rectangle();
$r1->length = 5;
$r1->breadth = 6;

echo "Enter the length and breadth value: " . $r1->length . " " . $r1->breadth . "\n";

$r1->area = $r1->length * $r1->breadth;
echo "Area of the Rectangle: " . $r1->area . "\n";
?>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.