I want to create a simple class that I can use and encode as a json string. My goal is to encode a json object with info about all my photos on the page. Never used object oriented php before, but I gave it a shot:
class Photo
{
public $file;
public $date;
function __construct($filename, $datetime)
{
$file = $filename;
$date = $datetime;
}
}
Looping through my photos and creating a new instance of the class for each photo:
$photo = new Photo($filename, $date);
2 problems: echo json_encode($photo); shows me that filename and datetime are null. And when I use echo json_encode($photo);, I will only get the last photo printed, right?
You need to use class member by using $this->varName in your class
So you constructor should be as
function __construct($filename, $datetime)
{
$this->file = $filename;
$this->date = $datetime;
}
as @code_burgar said : need to use array
$photo[] = new Photo($filename, $date);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With