2011-04-25 124 views
0
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数量的照片数组,而不是全部。但我不知道该怎么做。任何帮助表示赞赏!简单的OOP-PHP问题

+5

没有关于这方面的具体内容。 – 2011-04-25 00:17:51

回答

2

由于$this->photos只是一个数组,你可以使用array_slice得到你想要的子集:

function get_N($n) { 
    return json_encode(array_slice($this->photos, 0, $n)); 
} 

为了保持DRY,我会建议,移动编码“过程”的方法还有:

function encode($data) { 
    return json_encode($data); 
} 
function get_N($n) { 
    return $this->encode(...); 
} 

但这根本没有必要。

+0

array_slice,不知道那一个:)非常感谢,你们所有人 – Berntsson 2011-04-25 00:28:25

+0

PHP有许多非常方便的SPL(数组)功能:http://nl.php.net/manual/en/ref.array.php – Rudie 2011-04-25 00:29:53

0
/** 
* 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); 
}