Purpose : In order to make a class more secure,
Practice :
1. Change the member variable (age) to private
2. Do methods in the class to indirectly access member variables
3. Add control to the access
Class Ren
{
public $code;//Personnel Code
private $name;//Name
private $sex;//gender
PrivatePrivate) $age;//Age
Constructor method to initialize the gender
function __construct ($s)
{
$this->sex= $s;
}
Write not read//Create a method to modify age
function Setage ($a)
{
if ($a >18 && $a <50)//conditions to be limited to control to meet the conditions of the relay
Continue to
{
$this->age= $a;
}
}
Read-only do not write//create a method to get the age value
function Getage ()
{
return $this->age;
}*/
Recommended Use
Magic method for assigning values to variables (__set)
/* Function __set ($name, $v)//variable name, variable value
{
if ($name = = "Age")
{
if ($v >18 && $v <50)
{
$this $name = $v;
}
}
}*/
__get Magic method used to go to variable values
/*function __get ($n)
{
return $this $n;
}
}
Created objects
$r = new Ren ("male");
$r->setage ("20");
$r->set ("age", 30);
$r->age=40;//automatically calls the __set () method, treats the variable name as the first argument,
The value on the right side of the number as the second argument.
$->name= "Zhang San";
Echo $r->set;//automatically calls the __get method, and the variable name as a parameter;
Var_dump ($R);
Example of a joint tune
/*class Dog
{
Public $name;
function Jiao ()
{
echo $this->name. " In the name of ";
}
function SetName ($n)
{
$this->name= $n;
Retuen $this;
}
}
$d = new Dog ();
$d->setnam ("Wang Choi")->jiao ()
Three characteristics of the Face Object 1. Package