Tutorial :PHP Class won't return to a String



Question:

I'm fairly new to PHP so I have a small problem as I'm learning:

I built a Class called DataStrip.php

<?php    final class DataStrip  {      public function DataStrip()      {          // constructor        }        public function stripVars($vars)      {            return $vars;      }  }  ?>  

and then I'm trying to pass the public function stripVars a value:

<?php        include_once ('lib/php/com/DataStrip.php');        echo($projCat);      $a = new DataStrip;      $a->stripVars($projCat);      echo($a);    ?>  

however, I get back this error:

( ! ) Catchable fatal error: Object of class DataStrip could not be converted to string in myfilepath

... any advice perhaps on what I could be doing wrong here? Right now this is just a test function as I'm trying to get used to OOP PHP. :)


Solution:1

What do you expect it to happen? You're not saving the result of what stripVars returns into a variable:

$result = $a->stripVars($projCat);  print $result;  

What you are trying to do is print the object variable itself. If you want to control what happens when you try to print an object, you need to define the __toString method.


Solution:2

if you want to do that... you need declarate the method __toString()

    <?php        final class DataStrip      {      private $vars;                public function DataStrip()              {                      // constructor                }                public function stripVars($vars)              {                        $this->vars = $vars;              }                public function __toString() {                 return (string) $this->vars;              }          }    // then you can do     $a = new DataStrip;      $a->stripVars($projCat);      echo($a);        ?>  


Solution:3

Shouldn't you return to a variable:

$projCat = $a->stripVars($projCat);  

When you echo $a you're echoing the object - not any particular function or variable inside it (since when you declare $a you're declaring it as everything in the class - variables, functions, the whole kit and kaboodle.

I also have issues with php oop, so please correct if I am wrong :)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »