Rahil Wazir
Rahil Wazir

Reputation: 10132

get property of changed from other method within same class

This is my code. What i want is assigning the property $a value in method set_a() i need to get the same value within get_a() method without calling set_a() after object initialized or within get_a() and also dont want to pass any parameters to either methods. Is there any other methods do this?

class simple
{
    public $a;

    public function set_a()
    {
        $this->a = "ABC"; //need this value in get_a()
    }

    public function get_a()
    {
        echo $this->a; //should referenced from set_a()
    }
}

$foo = new simple();
echo $foo->get_a(); //output should be "ABC"
//or
echo $foo->a; //output should be "ABC"

Upvotes: 0

Views: 93

Answers (1)

Alma Do
Alma Do

Reputation: 37365

You should either initialize your property in class:

class simple
{
    public $a='ABC';
    //...
}

or do that in constructor:

class simple
{
    public $a;
    public function __construct($a='ABC')
    {
       $this->a=$a;
    }
}

-the second way is better since it allows you to initialize not only constant expressions (complex expressions can not be used in first case). However, if initializing value relies on something too complicated (function calls e t.c.) - you'll need to define desired behavior inside constructor.

See this reference for more clarifications of what is allowed in first case.

Upvotes: 3

Related Questions