Page 1 of 1

Using class object and method in function

Posted: 11 Oct 2017, 14:45
by Marius
Hello,
I try to create and use a class object instance and its method inside a function.
For example I have the following code, but it not works:

Code: Select all

class clsTest {
  protected $prop ='';

  function __construct($prop){
    $this->prop = $prop;var_dump($prop);
  }

  public function method($str){
    return $this->prop .' / '. $str;
  }
}

//Receives $prop-argument for object-instance, $str-argument for method()
function fun(){
  $str ='Text to method.';

  $ob = new clsTest($prop);
  $re = $ob->method($str);
  return $re .' / Text from function.';
}

$prop ='Prop for class.';
echo fun();
It shows this error:

Code: Select all

Notice: Undefined variable: prop

Using class object and method in function

Posted: 11 Oct 2017, 14:49
by Admin
Hello,
Pass to the function the arguments needed for class.
You can use one of the following examples:
1.

Code: Select all

class clsTest {
  protected $prop ='';

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

  public function method($str){
    return $this->prop .' / '. $str;
  }
}

//Receives $prop-argument for object-instance, $str-argument for method()
function fun($prop, $str){
  $ob = new clsTest($prop);
  $re = $ob->method($str);
  return $re .' / Text from function.';
}

$prop ='Prop for class.';
$str ='Text to method.';
echo fun($prop, $str); // Prop for class. / Text to method. / Text from function.
2.

Code: Select all

class clsTest {
  protected $prop ='';

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

  public function method($str){
    return $this->prop .' / '. $str;
  }
}

//Receives $ob-object-instance, $str-argument for method()
function fun($ob, $str){
  $re = $ob->method($str);
  return $re .' / Text from function.';
}

$prop ='Prop for class.';
$ob = new clsTest($prop);

$str ='Text to method.';
echo fun($ob, $str); // Prop for class. / Text to method. / Text from function.