我如何将这个getter重写为setter?

时间:2015-12-13 21:23:56

标签: php

我3周前才开始使用PHP,所以对我很温柔:)

我知道该方法应该接受一个数组索引和一些值作为参数来使用它们来更新数组但是我不知道语法并且已经尝试了很多次。

我不确定我是否仍然可以在方法中显示数组?

或者它应该在方法之外但在课堂内?

任何帮助都会很棒。

最佳, 德里克。

<?php
class Names{
    public $Names = array("Derek", "Paddy", "Des", "Billy" , "Jack");

    public function getElement($IndexParameter){
        return $this->Names[$IndexParameter];
    }

}

$obj = new Names;

echo $obj->getElement(4);

?>

2 个答案:

答案 0 :(得分:0)

你走了:

public function setElement($IndexParameter, $NewName) {
    $this->Names[$IndexParameter] = $NewName;
}

用法:

$obj->setElement(4, "Bilbo");

注意:我保留了你的风格,虽然我一般建议使用InitialCaps作为类名。

答案 1 :(得分:0)

$Names属性标记为protectedprivate,以防止直接访问该属性。

class Names{
    protected $Names = array("Derek", "Paddy", "Des", "Billy" , "Jack");

    public function getNames($IndexParameter){
        return $this->Names[$IndexParameter];
    }

    public function setNames($IndexParameter, $NewName) {
        $this->Names[$IndexParameter] = $NewName;
    }
}