You can set the value of the name property to just about anything you want like the previous example showed in Tutorial1.3 . However, you don't get an opportunity to do any sort of data validation or update any other values when the name property is set. In order to work around this problem ,Always implement your properties in the form of functions called get[ property name]and set[property name].Such functions are known as accessor methods
<?php
class Demo{
private $_name; // setting it as private,it can provent accessing from another object
function sayHello(){
print " $this->_name is My lovely girl ";
}
function getName(){ // this is Getter
return $this->_name;
}
function setName($name){ // this is setter
if(!is_string($name)||strlen($name)==0){
throw new Exception("Invalid name value!");
}
$this->_name=$name;
}
}
$obj=new Demo(); //create a object
$obj->setName("Nati");//set Name
$obj->sayHello(); // access a function of the object :$obj
?>
Output:
Nati is My lovely girl
No comments:
Post a Comment