Accessor methods

After an object is created, the PHP script can use or change the value of a public property. But, when the new value is set you can't do any sort of data validation or perform other instructions.
However, you can declare that property with private attribute and define a function to set its value.
Such functions are known as accessor methods, and ensures that your class can examine the value before allowing it to be set.
Once a property is declared with private attribute, it can't be accesed outside the class, so, to allow the script uses its value, you mast define another accesor method which gets and returns the value of that property.

It's better to define the accesor methods according to the property name which that accesor accesses.
- For accesors that set values you can use:   setProperty_name
- For accesors that get and return values you can use:   getProperty_name


  - Example:
The fallowing class, called Test, has a private property and two accesor methods that get and set the property value.
<?php
class Test {
  private $prop;         // property without an initial value

  // accesor to set value for $prop
  public function setProp($val) {
    $this->prop = $val;
  }

  // accesor to get the value of $prop
  public function getProp() {
    return $this->prop;
  }
}
?>
Now, in the PHP script we create an object instance of the Test class, then we call the accesor methods to set and get the value of $prop.
<?php
// icluding the code of the Test class

$obj = new Test();

// calls the setProp() accesor to set a value to "prop"
$obj->setProp('Free PHP course');

// calls the getProp() accesor to get the value of "prop"
$prop_val = $obj->getProp();

// print $prop_val
echo 'The value of the "prop" property is: '. $prop_val;
?>
This example will output:
The value of the "prop" property is: Free PHP course
This is just the simplest example to understand how accesor methods work, but their main purpose, especially for the accesor that sets the value, is to validate the data passed. You have to add some validation instructions to check the received value in the accesor, as it's shown below.

Checking data type in the accesor method

You can determine /check the type of a variable's value using one of PHP's type-checking functions listed below. Each function accepts a variable or value and returns TRUE if this argument is of the relevant type.

• The __constructor() also can be used as an accesor method to set property values.
Let's see a concrete example.
The following class, named "ArPer" has two private properties ($length and $width) without values, constructor and a public method, getArPer(). The constructor receives two arguments to set the values for the two properties. These values must be numeric type becouse the getArPer method is used to calculate and return the area and the perimeter of a quadrilateral with side length given by $length and $width properies.
<?php
class ArPer {
  // define private properties
  private $length, $width;

  // set constructor
  public function __construct($length, $width) {
    // if $length and $width are numeric type, set properties value
    // else, ends the script
    if (is_numeric($length) && is_numeric($width)) {
      $this->length = $length;
      $this->width = $width;
    }
    else {
      exit('Invalid argument value!');
    }
  }

  // define getArPer method
  public function getArPer() {
    // calculate and output the area and perimeter
    $area = $this->length * $this->width;
    $perimeter = 2 * ($this->length + $this->width);

    echo 'Area: '. $area. ' - Perimeter: '. $perimeter;
  }
}
?>
Now, in the script we create an object of this class and call the getArPer() method (the class must be included in the script).
If one of the arguments is not numeric type, the constructor executes exit('Invalid argument value!');, which will display a message and ends the script.
<?php
// include ArPer class

// create the object
$obj = new ArPer(7, 8);

// calls the getArPer method
$obj->getArPer();

echo '<hr />';

// create another object of the ArPer class, with a string argument
$obj2 = new ArPer(7, 'str');            // Invalid argument value!
?>
This example will output:
Area: 56 - Perimeter: 30
Invalid argument value!

Destructor Method

The Destructor Method is created with the __destruct() name. It's the opposite of __construct().
You have seen that the __construct() method is automatically invoked when an object is instantiated. The __destruct() method is automatically invoked just before the object is removed from memory ( with unset($object) ).
This method is useful when you want to perform any last-minute actions (such as saving or printing some data when it is deleted).
  - Example:
The Test class bellow outputs a message when an object instance is created, and prints another message when the instance is deleted.
<?php
// Test class
class Test {
  private $name;

  // Constructor
  public function __construct($name) {
    // assigns the value of the argument to the $name property
    $this->name = $name;

    echo 'Welcome '. $this->name. '<br />';
  }

  // accesor method - change the valure of '$name'
  public function setName($name) {
    $this->name = $name;
  }

  // Destructor method
  function __destruct() {
    echo 'Good by '. $this->name;
  }
}
?>
To test the effect of __destruct() method, use the following script (see explanations in script code).
<?php
// include Test class

// object instance of Test class
$obj = new Test('Mar');

// calls setName() to set a new value for 'name' property
$obj->setName('Plo');

// Delete the $obj instance
unset($obj);
?>
PHP detects when the $obj object is deleted (with unset($obj);) and automatically invokes the __destruct() method.
The example above will output:
Welcome Mar
Good by Plo

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
PHP OOP - Accessor and Destructor methods

Last accessed pages

  1. Backgammon (3874)
  2. PHP functions (1299)
  3. Construction Fall (119)
  4. Football Cars (818)
  5. Get Duration of Audio /Video file before Upload (3017)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (50849)
  2. Read Excel file data in PHP - PhpExcelReader (39684)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (37892)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (34162)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (31636)