[英]simple oop-php question
class Photos
{
private $photos = array();
function add_photo($filename, $date, $lat, $long)
{
$this->photos[] = array('filename' => $filename, 'date' => $date,
'lat' => $lat, 'long' => $long);
return $this;
}
function get_all()
{
return json_encode($this->photos);
}
}
我是面向對象的php的新手,所以我想在這里得到一些幫助。 get_all
函數返回我的所有照片。 我想添加一個函數來返回X個數量的照片數組,而不是所有這些數組。 但我不知道該怎么做。 任何幫助表示贊賞!
由於$this->photos
只是一個數組,您可以使用array_slice
來獲取所需的子集:
function get_N($n) {
return json_encode(array_slice($this->photos, 0, $n));
}
為了保持DRY ,我建議將編碼'process'移動到一個方法:
function encode($data) {
return json_encode($data);
}
function get_N($n) {
return $this->encode(...);
}
但這根本不是必需的。
/**
* Retrieve a photo from an index or a range of photos from an index
* to a given length
* @param int index
* @param int|null length to retrieve, or null for a single photo
* @return string json_encoded string from requested range of photos.
*/
function get($key, $length = null) {
$photos = array();
if ($length === null) {
$photos[] = $this->photos[$key];
}
else {
$photos = array_slice($this->photos, $key, $length);
}
return json_encode($photos);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.