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.
<?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 attribute is used in <img> tag for the address of the image?
href src rel
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;
#id {
  display: none;
}
What instruction stops the execution of a while() or for() statement?
continue prompt() break
for(var i = 0; i< 8; i++) {
  if(i > 1) break;
  alert(i);
}
Indicate the function that can create a constant.
define() include() defined()
define("CONSTANT_NAME", "value");
echo CONSTANT_NAME;
PHP OOP - Accessor and Destructor methods

Last accessed pages

  1. Writing CSS code (2701)
  2. Importing images (1569)
  3. Create simple Website with PHP (43784)
  4. Prayer The Art of Believing (1589)
  5. SHA1 Encrypt data in JavaScript (35259)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (470)
  2. Read Excel file data in PHP - PhpExcelReader (147)
  3. PHP Unzipper - Extract Zip, Rar Archives (145)
  4. SHA1 Encrypt data in JavaScript (122)
  5. Get and Modify content of an Iframe (108)
Chat
Chat or leave a message for the other users
Full screenInchide