如何在PHPOO中获取公共变量?

时间:2022-03-06 22:06:09

I'm trying to put a 'global' value in a PHP controller, because I use it constantly in different functions, so, I've to send it a lot of times in the view, I saw that I can do a public variable like an attribute in Java. I have to declare the variable:

我试图在PHP控制器中放置一个'全局'值,因为我在不同的函数中不断使用它,所以,我要在视图中发送很多次,我看到我可以做一个公共变量像Java中的属性。我必须声明变量:

var $team="";// or public $team="";

How can I put, and get the value of the PHP attribute?

如何放置并获取PHP属性的值?

1 个解决方案

#1


Class Example:

class MyClass
{
    private $_a;
    public $b;

    public function __construct()
    {
      // example of constructor
    }

    public function set($a)
    {
       $this->_a = $a;
    }

    public function get()
    {
       return $this->_a;
    }
}

Example of usage:

用法示例:

// usage construct class and invoke private function set();
$myExampleClass = new MyClass();
$myExampleClass->set('something');

// set public
$myExampleClass->b = "i set a public var";

It probably best to design your class with getters and setters so keeping your variables private, unless you have specific reasons. Here is a good reference for best practices and styleguide.

除非有特殊原因,否则最好使用getter和setter来设计你的类,以保持变量的私有性。这是最佳实践和样式指南的一个很好的参考。

I hope this helps.

我希望这有帮助。

#1


Class Example:

class MyClass
{
    private $_a;
    public $b;

    public function __construct()
    {
      // example of constructor
    }

    public function set($a)
    {
       $this->_a = $a;
    }

    public function get()
    {
       return $this->_a;
    }
}

Example of usage:

用法示例:

// usage construct class and invoke private function set();
$myExampleClass = new MyClass();
$myExampleClass->set('something');

// set public
$myExampleClass->b = "i set a public var";

It probably best to design your class with getters and setters so keeping your variables private, unless you have specific reasons. Here is a good reference for best practices and styleguide.

除非有特殊原因,否则最好使用getter和setter来设计你的类,以保持变量的私有性。这是最佳实践和样式指南的一个很好的参考。

I hope this helps.

我希望这有帮助。