filemonczyk
filemonczyk

Reputation: 1703

Parsing json data to objects in php

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?

Upvotes: 1

Views: 58

Answers (1)

Mark Phillips
Mark Phillips

Reputation: 273

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

Upvotes: 3

Related Questions