Azevedo
Azevedo

Reputation: 2189

How can I create a json-like variable inside a php class?

How can I create a json-like variable inside a php class? Example:

<?php 
    class person {
        var $details;
        var $name;
        function set_name($new_name) {
            $this->name = $new_name; 
        }
        function get_name() {
            return $this->name; 
        }
    }
?>

So $details would be something like:

{ address: '', birthdate: '', email: ''}

Then I'd access it like:

var x = new person();
$x->details->email;

Upvotes: 3

Views: 51

Answers (2)

Noman Ur Rehman
Noman Ur Rehman

Reputation: 6957

You will need to use the json_decode function.

First, assign a JSON construct to the instance variable, something like this:

<?php

class Person {
    public $details;
    public $name;
    function __construct($name, $details) {
        $this->name = $name;
        $this->details = json_decode($details);
    }

}

?>

Then on, you can access the object property like this:

<?

$person = new person('Noman', '{ "property1": "value1" }');

echo($person->details->property1);

?>

You can adapt the class design to your needs but this gives you the basic idea of how to do it.

Upvotes: 0

Barmar
Barmar

Reputation: 780919

Make it an associative array:

$details = array('address' => '123 Main St', 
                 'birthdate' => '2001-02-03', 
                 'email' => "[email protected]"
                );

Then you would access it as:

$x->details['email'];

Upvotes: 1

Related Questions