简体   繁体   English

我如何使变量可访问php类中的所有函数

[英]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. 我希望我的变量可以被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 或者,如果还有其他方法可以减少开销,请提出建议

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;
    }
}
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. 那会让你前进。

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. 当然,您可以将它们设置为私有,公共或受保护,这取决于您是否希望只能从此类或其他类中访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM