简体   繁体   中英

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. The get_all function returns all my photos. I would like to add a function that returns X numbers of photo-arrays, instead of all of them. 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:

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:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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