Searching...
Friday 26 July 2013

Defining Class Methods in PHP


A method is quite similar to a function, except that it is intended to define the behavior of a particular class (more about classes in PHP). Like a function (more about functions in PHP), a method can accept arguments as input and can return a value to the caller. Methods are also invoked like functions, except that the method is prefaced with the name of the object (more about objects in PHP) invoking the method, like this:

$object->methodName();

In this article you’ll learn all about methods, including method declaration, method invocation, and scope.

Declaring Methods

Methods are created in exactly the same fashion as functions, using identical syntax. The only difference between methods and normal functions is that the method declaration is typically prefaced with a scope descriptor. The generalized syntax follows:

scope function functionName()
{
// Function body goes here
}


For example, a public method titled calculateSalary() might look like this:

public function calculateSalary()
{
return $this->wage * $this->hours;
}

In this example, the method is directly invoking two class properties, wage and hours, using the $this keyword. It calculates a salary by multiplying the two property values together and returns the result just like a function might. Note, however, that a method isn’t confined to working solely with class properties; it’s perfectly valid to pass in arguments in the same way you can with a function.

Tip: In the case of public methods, you can forgo explicitly declaring the scope and just declare the method like you would a function (without any scope).

Invoking Methods

Methods are invoked in almost exactly the same fashion as functions. Continuing with the previous example, the calculateSalary() method would be invoked like so:

$employee = new Employee("Janie");
$salary = $employee->calculateSalary();

Method Scopes

PHP supports six method scopes: public, private, protected, abstract, final, and static. The first five scopes are introduced in this article. The sixth, static, is introduced in the article “More components of Object Oriented PHP”.

Public

Public methods can be accessed from anywhere at any time. You declare a public method by prefacing it with the keyword public or by forgoing any prefacing whatsoever. The following example demonstrates both declaration practices, in addition to demonstrating how public methods can be called from outside the class:

<?php
class Visitors
{
public function greetVisitor()
{
echo "Hello<br />";
}
function sayGoodbye()
{
echo "Goodbye<br />";
}
}
Visitors::greetVisitor();
$visitor = new Visitors();
$visitor->sayGoodbye();
?>


The following is the result:

Hello
Goodbye

Private

Methods marked as private are available for use only within the originating class and cannot be called by the instantiated object, nor by any of the originating class’s child classes (more about child classes in OOP model of PHP). Methods solely intended to be helpers for other methods located within the class should be marked as private. For example, consider a method called validateCardNumber() that is used to determine the syntactical validity of a patron’s library card number. Although this method would certainly prove useful for satisfying a number of tasks, such as creating patrons and self-checkout, the function has no use when executed alone. Therefore, validateCardNumber() should be marked as private, like this:

private function validateCardNumber($number)
{
if (! ereg('^([0-9]{4})-([0-9]{3})-([0-9]{2})') ) return FALSE;
else return TRUE;
}

Attempts to call this method directly from an instantiated object result in a fatal error.

Protected

Class methods marked as protected are available only to the originating class and its child classes. Such methods might be used for helping the class or subclass perform internal computations. For example, before retrieving information about a particular staff member, you might want to verify the employee identification number (EIN) passed in as an argument to the class instantiator. You would then verify this EIN for syntactical correctness using the verifyEIN() method. Because this method is intended for use only by other methods within the class and could potentially be useful to classes derived from
Employee, it should be declared as protected:

<?php
class Employee
{
private $ein;
function __construct($ein)
{
if ($this->verifyEIN($ein)) {
echo "EIN verified. Finish";
}
}
protected function verifyEIN($ein)
{
return TRUE;
}
}
$employee = new Employee("123-45-6789");
?>

Attempts to call verifyEIN() from outside of the class or from any child classes will result in a fatal error because of its protected scope status.

Abstract

Abstract methods are special in that they are declared only within a parent class but are implemented in child classes. Only classes declared as abstract can contain abstract methods. You might declare an abstract method if you want to define an application programming interface (API) that can later be used as a model for implementation. A developer would know that his particular implementation of that method should work provided that it meets all requirements as defined by the abstract method. Abstract methods are declared like this:

abstract function methodName();

Suppose that you want to create an abstract Employee class, which would then serve as the base class for a variety of employee types (manager, clerk, cashier, etc.):

abstract class Employee
{
abstract function hire();
abstract function fire();
abstract function promote();
abstract demote();
}

This class could then be extended by the respective employee classes, such as Manager, Clerk, and Cashier.

Final

Marking a method as final prevents it from being overridden by a subclass. A finalized method is declared like this:

class Employee
{
final function getName() {
...
}
}

Attempts to later override a finalized method result in a fatal error.

Type Hinting

Type hinting is a feature introduced with the PHP 5 release. Type hinting ensures that the object being passed to the method is indeed a member of the expected class. For example, it makes sense that only objects of class Employee should be passed to the takeLunchbreak() method. Therefore, you can preface the method definition’s sole input parameter $employee with Employee, enforcing this rule. An example follows:

private function takeLunchbreak(Employee $employee)
{
...
}

Keep in mind that type hinting only works for objects and arrays. You can’t offer hints for types such as integers, floats, or strings.


0 comments:

Post a Comment

 
Back to top!