In my class, I am trying to set the value of a variable in a function other than __construct()
But I need that variable value in another function.
Here is what I have tried. But not works Properly.
I expect to print getty images
but I get nothing :(
<?php
class MyClass{
public $var;
public function __construct(){
$this->var;
}
public function setval(){
$this->var = 'getty Images';
}
public function printval(){
echo $this->var;
}
}
$test = new MyClass();
$test->printval();
Your constructor does nothing, you need to invoke the method for it to do something.
class MyClass{
private $var;
public function __construct() {
// When the class is called, run the setVal() method
$this->setval('getty Images');
}
public function setval($val) {
$this->var = $val;
}
public function printval() {
echo $this->var;
}
}
$test = new MyClass();
$test->printval(); // Prints getty Images
You need to call your setval() method to actually set a value.
Try:
<?php
$test = new MyClass();
$test->setval();
$test->printval();
If your are happy having a fixed value, setting the variable in the __construct() will work fine and i would recommend this approach.
If however you want a dynamic value you could tweak your setval method to acccept a parameter and save the passed parameter to your object for rendering as part of the printval() call.
you need first to set value to your variable before you print it
<?php
class MyClass{
public $var;
public function setval(){
$this->var = 'getty Images';
}
public function printval(){
echo $this->var;
}
}
$test = new MyClass();
$test->setval();
$test->printval();
?>
output:
getty Images