The url to JSON structure
http://api.giphy.com/v1/gifs/search?q=funny+cat&offset=100&limit=1&api_key=dc6zaTOxFJmzC
Now I'm trying to parse this Json data to my objects:
this is my class:
<?php
class MappedEntity{
private $id;
private $mp4Url;
public function setId($id){
$this->id=$id;
}
public function setMp4Url($mp4Url){
$this->mp4Url=$mp4Url;
}
public function getId(){
return $id;
}
public function getMp4Url(){
return $mp4Url;
}
function __contruct($jsonData){
foreach($jsonData as $key => $val){
if(property_exists(__CLASS__,$key)){
$this->$key = $val;
}
}
}
}
?>
the code thats calling the class:
<?php
require_once 'mappedEntity.php';
$keyword = $_POST["keyword"];
$url="http://api.giphy.com/v1/gifs/search?q=".$keyword."&offset=100&limit=1&api_key=dc6zaTOxFJmzC";
$json = file_get_contents($url);
$file = json_decode($json);
$entity = new MappedEntity($file);
echo $entity->getId();
?>
Im getting
Notice:
Undefined variable: id in C:...\MappedEntity.php on line 14
which is following ine
13 public function getId(){
14 return $id;
15 }
OK, I changed the getter methods, and constructor , now the error goes
Notice: Undefined variable: id in C:\....\MappedEntity.php on line 14
Fatal error: Cannot access empty property in C:...\MappedEntity.php on line 14
I assume , my mapping method inside of constructor is not working fine?
asked Oct 26, 2016 at 12:34
filemonczyk
1,7235 gold badges32 silver badges54 bronze badges
1 Answer 1
You're missing the $this on both getID and getMp4URL functions, they should read:
public function getId(){
return $this->id;
}
and
public function getMp4Url(){
return $this->mp4Url;
}
answered Oct 26, 2016 at 12:37
Mark Phillips
2731 silver badge8 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Progrock
and the contructor?
Mark Phillips
Firstly fix the typo in the constructor (it should be __construct), you do not need to change the body of the method, it looks okay.
RiggsFolly
Except this still wont load the data correctly as the construtor code is also not getting data from the correct part of the structure
lang-php
return $this->id;__contruct, instead of__construct$this->idnot$idreturn $id;toreturn $this->id;also forreturn $mp4Url;toreturn $this->mp4Url;