OOPS in PHP 5 - Define Attributes for Class

Now you have declared class and now we have to define the attributes or the data member that will hold the data within the class. This tutorial will guide you to create attributes for the class.

What are Attributes for Class?
In OOPS attributes hold the data required for the class to perform its functionality. By declaring attributes you are declaring variables for the class. Attributes are used along with Access Specifiers. Different Access Specifiers used in ePHP5 are public, private and protected. Default Access Specifier for an attributes in PHP5 is public.




Example:

class newClass
{
   public $first_name;
   private $second_name;
   protected $third_name;
}

Here i have created 3 attributes for class newClass viz first_name, second_name and third_name.

IMPORTANT NOTE:
Attributes can also holds object on another class. This is useful when you want to pass the specific class object to the methods of another class.
Example - Attribute holding Object

< ?
class Employee {
 
}
 
class Payment {
	private $emp_id;
	private $Employee
 
	private setPayment(Employee $e)
	{
	   $this->Employee = $e;
	}
}
?>

Here in the payment class i am created setPayment() method, this method accepts one parameter which is the object of Employee class. This approach of assigning object to variables is called Type Hinting in PHP5.

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)