Home > PHP, PHP Tutorials, PHP5 OOPS Tutorials > PHP5 Tutorial – Defining Methods of a PHP5 Class

PHP5 Tutorial – Defining Methods of a PHP5 Class

November 8th, 2007 admin Leave a comment Go to comments

In this PHP5 tutorial you will learn about methods and how to declare and use them in PHP5 class.

Definition of an class method
A class method/functions is the behavior/functionality of a class i.e. they provide the necessary code for the class in which it is defined. Examples could be a saveCustomer() method in the class Customer or a printDocument() in the Document class.

Methods act (perform operations) on the data members of the class and can be declared as private or public. A class method is exactly similar to PHP functions, it’s just that class functions are declared inside classes and accessed using the -> (arrow operator / dereferencing operator).





Methods can also be declared as either public, protected or private.

Lets look at an example to understand PHP5 Class methods better:

Example Code:

class Customer {
	private $name;
	public functionsetName($name) {
		$this->name = $name;
	}
}
 
$c1 = new Customer();
$c1->setName("Sunil Bhatia");

In the above example setName() is the class method of the Customer class. The setName() class method is responsible for accepting the name of the customer and storing it in the internal data member i.e. $name.

The reason why you require methods is so that you can perform necessary validations on the data passed. Let’s re-look at the above example with necessary validation code.

class Customer {
	private $name;
	public function setName($name) {
		if(trim($name) != "") {
			$this->name = $name;
			return true;
		}
		else {
			return false;
		}
	}
}
 
$c1 = new Customer();
$c1->setName("Sunil Bhatia");

In the above example the setName() method accepts a customer’s name and validates to check if $name is blank. If $name is blank the setName() function returns false; otherwise it stores the $name in the $this->name of the class and returns true.

Notes on Accessor and Mutator methods

Although we will learn about Access Specifiers in the subsequent tutorials; let’s try to understand the meaning and need for accessor and mutator methods.

Accessor Methods:
Accessor methods are also know as getter methods. The reason why we need an accessor method is to be able to read the value of a property/attribute in a class object. In real OOAD practice most of the data members that you define would either be private or protected (more on this will be covered in the tutorial on Access specifiers), therefore to access data of such data members that have been defined as either private or protected will require an implementation of accessor or getter methods.

Note: To make a property or data member as non-read only; you should not provide a getter or accessor method.

Mutator Methods:

Mutator methods are opposite to accessor methods. Mutator methods provides a mechanism to store data in data members that have either been declared as private or protected. The reason why you should provide a mutator method is to provide necessary validation on the data that is to be stored in the data member of the class.

Note: To make a property or data member as read only; you should not provide a setter or mutator method.

Lets look at an example of accessor and mutator methods below:

class Customer {
	private $name;
 
	//mutator method
	public function setName($name) {
		if(trim($name) != "") {
			$this->name = $name;
			return true;
		}
		else {
			return false;
		}
	}
 
	//accessor method
	public getName() {
		return $this->name;
	}
}
 
$c1 = new Customer();
$c1->setName("Sunil Bhatia");
echo $c1->getName();

Output:
Sunil Bhatia

In the above example the setName() method accepts a customer’s name and validates to check if $name is blank. If $name is blank the setName() function returns false; otherwise it stores the $name in the $this->name of the class and returns true. The getName() returns the name stored in the $name data member of the $c1 object.

In the next tutorial you will learn about PHP5 Constructor.

Feel free to write comments if you need more examples or if you need to ask a question on PHP5 Class. You can also subscribe to my notification service to be informed as an when a new tutorial article goes online. Subscribe Below




Related Posts on PHP5 Tutorial – Object Oriented Programming (OOPS)

  1. PHP5 Tutorial – Learn to create a PHP5 Class
  2. PHP5 Tutorial – Learn to Create a PHP5 Class Object
  3. PHP5 Tutorial – Defining Attributes of a PHP5 Class
  4. PHP5 Tutorial – Defining Methods of a PHP5 Class
  5. PHP5 Tutorial – Creating a PHP5 Constructor __construct()
  6. PHP5 Tutorial OOPS – Creating a PHP5 Destructor __destruct()
  7. PHP5 Tutorial OOPS – PHP5 Class Access Specifiers – public, private and protected
  8. PHP5 Tutorial – Magic Methods – __toString() method
  9. PHP5 Tutorial – Magic Methods – __get() and __set()
  10. PHP5 Tutorial – Magic Methods – __isset() and __unset()
  11. PHP5 Tutorial – Magic Methods – __call() method
  12. PHP5 Tutorial – Magic Methods – __autoload() method
  13. PHP5 Tutorial – Magic Methods – __sleep() and __wakeup()
  14. PHP5 Tutorial – Magic Methods – __clone() method

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. Basit
    February 28th, 2008 at 12:36 | #1

    Hi

    i wanted to ask a question about mutator method, you defined it twice on the example, im confused.. whats the different between them, they look the same.

    i thought first one would be because of validation and then once it returns true then it will call it again and next one will insert the data. but your example as both things same, not a difference between them. can you explain more bit on them please.

    Best Regards
    Basit

  2. admin
    February 28th, 2008 at 15:42 | #2

    Hi Basit,

    My apologies, there was a mistake in the code. I have corrected the same. I had copied the mutator method twice.

    Sunil

  3. Oli
    April 18th, 2008 at 22:19 | #3

    Hi, first of all I want to thank you for the brilliant tutorials.

    I am just curious…

    Shouldn’t there be “function” exclusively mentioned on this line

    public setName($name)

    like Public function setname($name)

    Sorry Im very new to PHP, when I copied and paste the above
    codes to my php editor and run the script it comes with error.

    Parse error: parse error, unexpected T_STRING, expecting T_VARIABLE in C:\Apache2\htdocs\Testing\OOP_Attributes.php on line 6

    So I thought I try by exclusively mentioning “function” and
    it worked.

  4. Shankar
    March 6th, 2009 at 18:11 | #4

    Nice. Interesting tutorial.

    Now, I am really confident with the PHP OOPS concept.

    Thank You.

  5. Amit
    April 15th, 2009 at 18:54 | #5

    Hello,

    This is a nice website.

    In the example related to class I feel the keyword ‘function’ will be added before the function name. As for example it should be
    public function setName()
    instead of
    public setName()

    Please ask your queries. Please let me know whether I am right or wrong.

    Regards.

  6. admin
    April 16th, 2009 at 10:07 | #6

    Hi Amit,

    Thank you for pointing out the mistake. I have fixed the same.

    Regards,
    Suniil

  7. March 5th, 2010 at 23:58 | #7

    Took me hours to work out why your code did not work.

    Can you change the page so that other people don’t have the same problems?

    Apart from that its a cool lession.

  8. March 15th, 2010 at 15:57 | #8

    good

  1. November 8th, 2007 at 23:01 | #1
Enter this code to leave comment (Sorry, but bots get me crazy :) )