方法重载:function __call($ method,$ arg)

时间:2012-11-19 18:41:25

标签: php

我有两个班:地址和学生。我需要编写__call()函数代码,以便可以使用学生实例检索和分配街道,城市和州的属性。

这是我的输出(我编码__call()但它只适用于目前为止的最后一行输出):

John Smith
50
, ,
The address has been updated:
50 second street, Palo Alto, CA

输出的第三行应为:

100 main street, Sunnyvale, CA

这就是我堆叠的地方。

这是我的代码。我将不胜感激。

<?php
class Address {
private $street;
private $city;
private $state;

function __construct($s, $c, $st) {
    $this->street = $s;
    $this->city = $c;
    $this->state = $st;
}
function setCity($c) {
    $this->city = $c;
}
function getCity() {
    return $this->city;
}
function setState($s) {
    $this->state = $s;
}
function getState() {
    return $this->state;
}
function setStreet($s) {
    $this->street = $s;
}
function getStreet() {
    return $this->street;
}
}
class Student {
private $name;
private $age;
private $address;

function __construct($n, $a, Address $address) {
    $this->name = $n;
    $this->age = $a;
    $this->address = $address;
}

function getName() {
    return ucwords($this->name);
}

function getAge() {
    return $this->age;
}

function setName($n) {
    $this->name = $n;
}

function setAge($a) {
    $this->age = $a;
}

function __set($name, $value) {
    $set = "set".ucfirst($name);
    $this->$set($value);
}

function __get($name) {
    $get = "get".ucfirst($name);
    return $this->$get();
}

function __call($method, $arguments) {
    // Need more code 

    $mode = substr($method,0,3);
    $var = strtolower(substr($method,3));
    if ($mode =='get'){
        if (isset($this -> $var)){
            return $this ->$var;
        }
    } elseif ($mode == 'set') {
        $this ->$var = $arguments[0];
        }
    } 

}
$s = new Student('john smith', 50, '100 main street', 'Sunnyvale', 'CA');
echo $s->name;
echo "\n";
echo $s->age;
echo "\n";
echo $s->address->street . ", " . $s->address->city . ", " . $s->address->state;
echo "\n";
$s->street = "50 second street";
$s->city = "Palo Alto";
$s->state = "CA";
echo "The address has been updated:\n";
echo $s->street . ", " . $s->city . ", " . $s->state;


//print_r($s);

?>

1 个答案:

答案 0 :(得分:0)

streetcitystate必须为public,或使用获取者。

接下来改变:

$s = new Student('john smith', 50, '100 main street', 'Sunnyvale', 'CA');

代表下一个:

$s = new Student('john smith', 50, new Address('100 main street', 'Sunnyvale', 'CA'));

然后改变:

echo $s->address->street . ", " . $s->address->city . ", " . $s->address->state;

代表下一个:

echo $s->address->getStreet() . ", " . $s->address->getCity() . ", " . $s->address->getState();

学生构造函数需要一个Address对象,属性“street”,“city”和“state”是“private”,需要使用“getters”。

- )

相关问题