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, it $details
will look something like this:
{ address: '', birthdate: '', email: ''}
Then I would access it like:
var x = new person();
$x->details->email;
+3
source to share
2 answers
You need a function json_decode
.
First, assign the construct to JSON
an 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 you can access the property of the object like this:
<?
$person = new person('Noman', '{ "property1": "value1" }');
echo($person->details->property1);
?>
You can adapt the design of the class to your needs, but that gives you a basic idea of how to do it.
0
source to share