0

我有两个班级:地址和学生。我需要编写 __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);

?>
4

1 回答 1

0

,和必须是street,或使用吸气剂。citystatepublic

接下来改变:

$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();

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

;-)

于 2012-11-19T18:56:15.273 回答