我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);
?>
答案 0 :(得分:0)
你走了:
public function setElement($IndexParameter, $NewName) {
$this->Names[$IndexParameter] = $NewName;
}
用法:
$obj->setElement(4, "Bilbo");
注意:我保留了你的风格,虽然我一般建议使用InitialCaps作为类名。
答案 1 :(得分:0)
将$Names
属性标记为protected
或private
,以防止直接访问该属性。
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;
}
}