rana shekhar
rana shekhar

Reputation: 1

How can I make variables accessible to all the functions within the class in php

I want my variables to be accessible to all the functions within the class in php. I am giving a sample code of what Im trying to achieve. Please help me out.

class ClassName extends AnotherClass {

    function __construct(argument)
    {

    }

    $name = $this->getName();
    $city = $this->getCity();
    $age = 24;


    public function getName() {
        return 'foo';
    }

    public function getCity() {
        return 'kolkata';
    }

    public function fun1() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun2() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun3() {
        echo $name;
        echo $city;
        echo $age;
    }
}

Or if there is any other way to have least overhead .Please suggest

Upvotes: 0

Views: 84

Answers (3)

Gothiquo
Gothiquo

Reputation: 868

You have to set your variables as class attributes:

class ClassName extends AnotherClass {
    private $name;
    private $city;
    private $age;

    //Here we do our setters and getters
    public function setName($name)
    {$this->name = $name;}
    public function getName()
    {return $this->name;}

   // you call the setters in your construct, and you set the values there

Of course you can set them as private, public or protected, depends if you want them to be accessible only from this class or others.

Upvotes: -1

lagbox
lagbox

Reputation: 50491

class ClassName extends AnotherClass
{
    protected $name;
    protected $city;
    protected $age = 24;

    public function __construct()
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
    }

    ...

    public function fun1()
    {
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    ...
}

That would get you going a bit.

Upvotes: 0

Maraboc
Maraboc

Reputation: 11083

You can acheave you goal like this :

class ClassName extends AnotherClass {

    private $name;
    private $city;
    private $age;

    function __construct(argument)
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
        $this->age = 24;
    }

    public function getName(){
        return 'foo';
    }
    public function getCity(){
        return 'kolkata';
    }

    public function fun1(){
        echo $this->name; 
        echo $this->city;
        echo $this->age;
    }
    public function fun2(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    public function fun3(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
}

Upvotes: 2

Related Questions