Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP PHP - JSON-encoding an object

Tags:

json

oop

php

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?

like image 329
fille Avatar asked Jun 28 '26 08:06

fille


1 Answers

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);
like image 77
Gaurav Avatar answered Jul 01 '26 00:07

Gaurav