OOP PHP set variable value in one function and get

2019-08-19 07:08发布

问题:

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();

回答1:

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


回答2:

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.



回答3:

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


标签: php oop