PHP/Class/Getter Setter — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 10:37, 26 мая 2010
Call getter to get value for property
<?php
class Employee {
public $title;
public $lastName;
public $firstName;
public $price;
function __construct( $title, $firstName, $mainName, $price ) {
$this->title = $title;
$this->firstName = $firstName;
$this->lastName = $mainName;
$this->price = $price;
}
function getFullName() {
return "{$this->firstName}" . " {$this->lastName}";
}
}
$product1 = new Employee("B", "B1", "B2", 5.99 );
$product2 = new Employee("A", "A1", "A2", 10.99 );
print "author: ".$product1->getFullName()."\n";
print "artist: ".$product2->getFullName()."\n";
?>
Define and call getter method
<?php
class Staff
{
var $name;
var $city;
protected $wage;
function __get($propName)
{
echo "__get called!<br />";
$vars = array("name","city");
if (in_array($propName, $vars))
{
return $this->$propName;
} else {
return "No such variable!";
}
}
}
$employee = new Staff();
$employee->name = "Joe";
echo $employee->name."<br/>";
echo $employee->age;
?>
Define getter and setter
<?php
class Staff {
private $name;
// Getter
public function getName() {
return $this->name;
}
// Setter
public function setName($name) {
$this->name = $name;
}
}
?>