0

If you look at the usage for this library, https://github.com/Gregwar/Formidable

You have,

$form = new Gregwar\Formidable\Form('forms/example.html');

$form->handle(function() {
    echo "Form OK!";
}, function($errors) {
    echo "Errors: <br/>";
    foreach ($errors as $error) {
        echo "$error<br />";
    }
});

echo $form;

My question is, how is this done? How do you echo the $form object..

for eg if I have

class Something
{
   public $somevariable = 'London';

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

   public function foo(){
        //Do Something

   }
}

$myObj = new Something();
echo $myObj;

The above code gives me an error. What can I do to echo $myObj and not get an error so I can have something displayed on the screen?

We all know we can do something like,

echo $myObj->somevariable;

without an error.. How can I do

echo $myObj;

without getting an error as it is done in the Formidable library.

Sandeep kurien
  • 603
  • 1
  • 5
  • 8

2 Answers2

2

Magic method __toString() in your class. This allows your class to execute the code in that method when your object is treated like a string (i.e. when used with echo). The method must return a string, otherwise it will raise an error.

You will notice in the library you linked, that they have one in their form class.

/**
 * Convert to HTML
 */
public function __toString()
{
    return $this->getHtml();
}
Symeon Quimby
  • 820
  • 11
  • 17
0

You can add __tostring() magic function to your class

class Something
{
  public $somevariable = 'London';

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

  public function foo(){
    //Do Something

  }
  public function __tostring(){
    return $this->somevariable;
  }
}

Calling echo $myObj will print London

Shady Atef
  • 2,121
  • 1
  • 22
  • 40