Php-mysql Course

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.
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.
// 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.
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.
// include ArPer class

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

// calls the getArPer method

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.
// 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).
// include Test class

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

// calls setName() to set a new value for 'name' property

// Delete the $obj instance
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

What attribute makes the input text box to not be modified by the user?
checked="checked" readonly="readonly" disabled="disabled"
<input type="text" value="fixed-value" readonly="readonly" name="a_name" />
What CSS property allows you to create rounded corners in your webpage design?
background-size border-size border-radius
.class {
  border:2px solid blue;
What instruction displays a confirmation dialog box to the viewer, who must then click OK or Cancel to proceed?
indexOf() confirm() prompt()
var ques = window.confirm("The result of 0+0 is 0?");
if (ques) alert("Corect");
else alert("Incorrect");
Indicate the PHP function that returns the lowest number of the parameter values.
floor() ceil() min()
$min_nr = min(12, 8, 25, 13);
echo $min_nr;        // 8
PHP OOP - Accessor and Destructor methods

Last accessed pages

  1. CSS Course - Free lessons (20471)
  2. Wake Up! (14391)
  3. JavaScript Course - Free lessons (29685)
  4. The Four Agreements (1040)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (66106)

Popular pages this month

  1. PHP Unzipper - Extract Zip, Rar Archives (94)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (58)
  3. JavaScript Course - Free lessons (45)
  4. SHA1 Encrypt data in JavaScript (44)
  5. Read Excel file data in PHP - PhpExcelReader (38)