PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to return objects or arrays from a chaining interface in PHP OOP?

 July 22, 2022     fluent-interface, magic-methods, method-chaining, php, php-5.4     No comments   

Issue

I am curious in writing a chaining interface in PHP OOP. I modified this sample code from the php.net website, and I want to take it further - how can I return objects or arrays from this kind of interface?

// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$input = (object)array("title" => "page 1");
$class = new TestClass($input);
echo $class;

error,

Catchable fatal error: Method TestClass::__toString() must return a string value in C:\wamp\www\test\2013\php\fluent_interface.php on line 2

Should I use different magic method instead of __toString then?

EDIT: Can I return this as my result,

stdClass Object ( [title] => page 1 )

Solution

To get what you want you need to use following syntax:

print_r($class->foo);

The __toString() magic method tries to convert your whole class 'TestClass' to a string, but since the magic method is not returning a string, it is showing you that error. Of course you could also rewrite your __toString() method to do the following:

public function __toString()
{
    return print_r($this->foo, true);
}

http://php.net/manual/en/function.print-r.php

http://www.php.net/manual/en/language.oop5.magic.php#object.tostring



Answered By - Dragony
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing