Search code examples
phpclassconstruct

Access function from public construct in php


I have a php program where I have a function and a class with a public construct function in it, I need to call the function from inside the public construct as in code below :

class test {

    public $var0 = null;

    public function __construct() {

        $this->var0 = Tfunction('lol');

    }

}

function Tfunction ($String) {

    $S = ($String . ' !');

    return $S;

}

$j = new test();

echo($j);

when I run this it does not run the function, I tried evereything but it does not whant to put 'lol !' into my public variable, how could I get this to work?

One thing to note I dont get any errors telling me that the class cant access the fontion or anything like that, it just seems like the line is ignored away and $var0 is filed with null.


Solution

  • The error outputted when I ran your code was;

    'Object of class test could not be converted to string'

    There are 2 ways you can solve this problem, you can use either;

    1. Instead of the line echo($j); change it to echo($j->var0);

    Now instead of trying to print the object you are now printing the public variable from the object which was set in the constructor.

    1. Add a __toString() method to your object, and use this to output the var0 field.

      class test {
      
        public $var0 = null;
      
        public function __construct() {
      
          $this->var0 = Tfunction('lol');
      
        }
      
        public function __toString(){
      
          return $this->var0;
      
        }
      
      }
      
      function Tfunction ($String) {
      
        $S = ($String . ' !');
      
        return $S;
      
      }
      
      $j = new test();
      
      echo($j);
      

    Now when you try to print the object with echo($j); it will use the __toString() you assigned to output your variable.

    Both of theses fixes mean that 'lol!' was outputted to my browser window, as was originally expected.