pTutorial

New way to learn PHP

PHP 5 Classes

PHP 5 Classes

Class

A class is a unit of code that describes the characteristics and behaviours of something, or of the group of things. A class called Car, for example, would describe the characteristics and behaviours common to all cars.

PHP Data member

Data members are also variable but difference is that they are in encapsulated form.

PHP Property

A property is a variable inside the class which can contain some information. Like Name is the property of student class.

PHP Method

Methods are functions inside the body of class, methods can also be accessible by those three types of users.

C

It is a convention that the name of the function or method will start with a small letter and then the rest is camel case.

Creation of PHP Classes

Class

Classes and objects are easy to create in PHP. A class contains both properties and methods. There are no rules about the order in which they should appear first in the class.

C

It is a convention that Object Oriented classes begin with a capital letter.

Rule

To create a class, you use PHP’s class keyword.

PHP class syntax

class class _name
{
Properties 
methods
}

PHP Properties Declaration

To add a property to a class, first write the keyword public, private or protected depending on the visibility level you want to give to the property.

PHP properties declaration syntax

class Computer
{
public $user_name; // This is a public property

private $password; // This is a private property

}

You can also initialize properties at the time of declaration of properties much like general variables.

class Computer
{
public $user_name = "Admin"; 

private $password; 
}

In this case, whenever a new object is created from Computer class, the default value of $user_name is Admin.

PHP Access Properties

Once you have created class properties, you can access these properties with the help of object

$object-> property;

Note: Do not use $ symbol in front of properties.

PHP 5 class example

<?php

class Student
{
public $name = "John
"; public $roll = "20"; } $obj =new Student(); echo $obj->name; echo $obj->roll; ?>

Output

John
20

In this example, we are creating student class and initializing the value of these object by invoking set function.

PHP class example

<?php

class Student
{
public $name;
public $roll; 
public function set($name1,$roll1)
{ 
$this->name = $name1; 
$this->roll = $roll1;
}

Public function get()
{
echo $this->name;	
echo $this->roll;	
}

}
  $obj =new Student();
  $obj->set("umar",12);
  echo $obj->get();
	  
?>

Output

umar12

In the above example, Computer is the name of the class. get() and set are the method of the class. $name and $roll are property or attribute of the class. You can also access the property of class with the help of method or function, as shown above.


QUOTES OF THE DAY

A single death is tragedy, a million death is a static.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER