how cann I convert php class to json [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I am trying to convert a simple class object to json as string.
It does not work!. could you help me please.
here are my files:
Peson.php
<?php
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode($this);
}
}
?>
index.php
include 'Person.php';
$person = new Person();
$person->setName("John");
echo $person->toJson();
Result :

You're getting an empty object because your class doesn't have any public properties to encode. Change name from private to public and you'll get output like this: {"name":"John"}

You can use get_object_vars for this.
public function toJson()
{
return json_encode(get_object_vars($this)); //returns {"name":"stringNameHere"}
}
More info about get_object_vars here.
This is how your code would look:
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode(get_object_vars($this));
}
}
$person = new Person();
$person->setName('testName');
echo $person->toJson(); //Print {"name":"testName"}
Here you have a live code example

In this case you get an empty object because the properties are private. A way to keep your properties private and still geting their values in a JSON is using the JsonSerializable Interface. Then implementing its method jsonSerialize().
class Person implements JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
}

<?php
class Person implements \JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
?>
then, you can convert your person object to JSON with json_encode
$person = new Person();
$person->setName("John");
echo json_encode($person);

Related

Php closure in a class method call

Lets say I have two classes Car and Owner
owner.php =>
class Owner {
public $name;
public function setName($name) {
$this->name = $name;
}
}
and respectively the car.php =>
class Car {
public $owner;
public function setOwner(Owner $owner) {
$this->owner = $owner;
}
}
To set and call methods I normally use this approach =>
$owner = new Owner;
$owner->setName('sam');
$car = new Car;
$car->setOwner($owner);
But what if I want it to do using Closure like below, how do I change the setOwner method accordingly?
$car = new Car;
$car->setOwner(function(Owner $owner) {
$owner->setName('sam');
});
What I want to do is something similar to Laravel where
User::where('car_id', $carId)
or
User::where(function($query) {
//code here
})
Car::setOwner() needs to call its argument with an Owner object.
class Car {
public function setOwner(Callable $ownerSetter) {
$o = new Owner;
$ownerSetter($o);
}
}
But this is a strange way to use a closure. A better example might be:
class Car {
private $owner;
public function setOwner($owner) {
$this->owner = $owner;
}
public function doSomethingToOwner(Callable $something) {
$something($this->owner);
}
}
$car->setOwner($owner);
$car->doSomethingToOwner(function($owner) {
echo $owner->name;
});

understanding dependency injection in PHP

class Author {
private $firstName;
private $lastName;
public function __construct($firstName, $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName() {
return $this->firstName;
}
public function getLastName() {
return $this->lastName;
}
}
class Question {
private $author;
private $question;
public function __construct($question, Author $author) {
$this->author = $author;
$this->question = $question;
}
public function getAuthor() {
return $this->author;
}
public function getQuestion() {
return $this->question;
}
}
Class author is injected into the constructor of Question class am I correct? but how to call the Question class to get the author's name?
$question = new Question('What is PHP', 'Adam');
$question->getFirstname;
like this? I assume Question class inherited Author class so Question's instance can use the function of Author Class?
Simple
echo $question->getAuthor()->getFirstName();
Think of it this way if it helps
$author = $question->getAuthor();
echo $author->getFirstName();
Also note that you can't construct a Question with the string "Adam", you need to pass an instance of Author
$question = new Question('What is PHP', new Author('Adam', 'Lastname'));
You could create a new method:
class Question
{
// ...
function getAuthorFirstname()
{
return $this->author->getFirstname();
}
}
$question = new Question(.., new Author(..., ...));
echo $question->getAuthorFirstname();
Or, if you don't really care about Law of Demeter or feel that it doesn't apply:
$question = new Question(.., new Author(..., ...));
echo $question->getAuthor()->getFirstname();
In the end it all comes down to striking a balance between information hiding and pragmatism.

How to get object value from another object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
It's been a while since I last work with object. I can't figure out what I did wrong. I have a class that contain another class as a property. After instantiating ItemDetail() inside Item(), I can't get the value of description. var_dump($item) give me NULL for the value of $detail. Please help. Thank you.
<?php
class Item
{
private $name;
private $detail;
function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
function getDetail() {
return $this->detail;
}
}
class ItemDetail
{
private $description;
function __construct() {
$this->description = 'some description';
}
function getDescription {
return $this->description;
}
}
$item = new Item();
echo $item->getDetail()->getDescription();
//var_dump($item);
?>
You need to change the scope of your class properties, or define a method that returns the values. Example:
class Item
{
private $name;
private $detail;
function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
public function getDescription() {
return $this->detail->getDescription();
}
}
class ItemDetail
{
private $description;
function __construct() {
$this->description = 'some description';
}
public function getDescription() {
return $this->description;
}
}
$item = new Item();
echo $item->getDescription();
If you make your properties public, you can get them like this as well:
class Item
{
public $name;
public $detail;
public function __construct() {
$this->name = 'some name';
$this->detail = new ItemDetail();
}
}
class ItemDetail
{
public $description;
public function __construct() {
$this->description = 'some description';
}
}
$item = new Item();
echo $item->detail->description;
It's all about visibility

Use method of parent class when extending

Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them?
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
<?php
class Testb extends Test {
public function __construct() {
parent::__construct($name);
}
}
<?php
include('test.php');
include('testb.php');
$a = new Test('John');
$b = new Testb('Batman');
echo $b->getName();
You need to give the Testb constructor a $name parameter too if you want to be able to initialize it with that argument. I modified your Testb class so that its constructor actually takes an argument. The way you currently have it, you should not be able to initialize your Testb class. I use the code as follows:
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Testb extends Test {
// I added the $name parameter to this constructor as well
// before it was blank.
public function __construct($name) {
parent::__construct($name);
}
}
$a = new Test('John');
$b = new Testb('Batman');
echo $a->getName();
echo $b->getName();
?>
Perhaps you do not have error reporting enabled? In any event, you can verify my results here: http://ideone.com/MHP2oX

How to call object methods for an object in an array using a foreach loop

I am trying to store a collection of objects and can't call object methods in a foreach loop. This is basically what I have. The print function prints nothing. Is there something I am over looking or is this not the way to go about it?
class person
{
private $name;
public function __construct($name) {
$this->name = $name;
}
public function get_name() {
return $this->name;
}
}
$test_set[] = new person("John");
$test_set[] = new person("Jane");
foreach($test_set as $set_item) {
print $set_item->get_name();
}
You need to set your name like this (probably just a typo):
public function __construct($name) {
$this->name = $name; // not $this->$name
}
Your loop is working. But your class contains a mistake.
Replace:
public function __construct($name) {
$this->$name = $name;
}
With:
public function __construct($name) {
$this->name = $name;
}

Categories