OOPS in PHP5 – Define Attributes for Class  

Check out latest Mobile Phones and Books only at Flipkart.com
Flipkart.com

We have seen on how to declare 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.

  • Private – By declaring attribute as private the attribute can only be accessed within the class. So outside world cannot access this Attribute
  • Protected – By declaring attribute as protected the attribute can only be accessed by the derived class while performing inheritance operation but the outside world has no access to these Attribute
  • Public – By declaring attribute as public the attribute can be accessed internally and by outside world

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.


Related Articles:

Categories: PHP Tags: , ,
  1. jame
    September 27th, 2010 at 03:47 | #1

    your website is very good for your lesson but it’s very bad for many advertising on your page i’m very hate for that , please update your site please.

    thanks

  1. April 17th, 2010 at 22:52 | #1
  2. April 29th, 2010 at 01:49 | #2
  3. November 2nd, 2010 at 09:27 | #3
  4. June 6th, 2011 at 03:52 | #4

 

Page optimized by WP Minify WordPress Plugin