Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting variable access

I need to have a variable that only one function can write (let's call that function a) and that only one other function can read (let's call that function b). Is that possible?

like image 886
Emanuil Rusev Avatar asked Jul 16 '26 23:07

Emanuil Rusev


2 Answers

You could use a static variable:

function foo($val=null) {
    static $var = null;
    if (!is_null($var)) $var = $val;
    return $val;
}

Here $var is only visible inside the function foo and is maintained throughout multiple calls:

foo(123);
echo foo();  // 123
foo(456);
echo foo();  // 456

Or use a class with a private member and access/modify it with public methods:

class A {
    private $var;
    public function setVar($val) {
        $this->var = $val;
    }
    public function getVar() {
        return $this->var;
    }
}

With this the private member var is only visible to a particular instance of this class:

$obj1 = new A();
$obj1->setVar(123);
$obj2 = new A();
$obj2->setVar(456);
echo $obj1->getVar();  // 123
echo $obj2->getVar();  // 456

If you make the member static, then there is just one for the class instead of for each instance:

class A {
    private static $var;
    public function setVar($val) {
        self::$var = $val;
    }
    public function getVar() {
        return self::$var;
    }
}
$obj1 = new A();
$obj1->setVar(123);
$obj2 = new A();
$obj2->setVar(456);
echo $obj1->getVar();  // 456
echo $obj2->getVar();  // 456
like image 124
Gumbo Avatar answered Jul 18 '26 12:07

Gumbo


You can use a static abstract class.

abstract class Settings
{
    private static var $_settings = array();

    public static function get($key,$default = false)
    {
        return isset(self::$_settings[$key]) ? self::$_settings[$key] : $default;
    }

    public static function set($key,$value)
    {
        self::$_settings[$key] = $value;
    }
}

Example Usage:

Settings::set('SiteName',`SomeResult`);

echo Settings::get('SiteName');
like image 21
RobertPitt Avatar answered Jul 18 '26 13:07

RobertPitt