简体   繁体   English

简单的oop-php问题

[英]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);
   }
   }

I'm new to object oriented php, so i would like to get some help here. 我是面向对象的php的新手,所以我想在这里得到一些帮助。 The get_all function returns all my photos. get_all函数返回我的所有照片。 I would like to add a function that returns X numbers of photo-arrays, instead of all of them. 我想添加一个函数来返回X个数量的照片数组,而不是所有这些数组。 But I dont know how to do it. 但我不知道该怎么做。 Any help is appreciated! 任何帮助表示赞赏!

Since $this->photos is just an array, you can use array_slice to get the subset you want: 由于$this->photos只是一个数组,您可以使用array_slice来获取所需的子集:

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

To stay DRY , I would recommend, moving the encoding 'process' to a method as well: 为了保持DRY ,我建议将编码'process'移动到一个方法:

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

but that's not necessary at all. 但这根本不是必需的。

/**
 * 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM