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 tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP OOP - Accessor and Destructor methods

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)