Variable access restriction

I need to have a variable in which only one function can write (let me call this function a) and that only one can read another function (call the function b). Is it possible?

+3
source share
4 answers

You can use a static variable :

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

It is $vardisplayed only inside the function fooand is supported for several calls:

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

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

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

var :

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

static, , :

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
+6

.

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;
    }
}

:

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

echo Settings::get('SiteName');
+1

5.3.0, . , b..., a... , :

<?php
function a()
{
    // Only a() can write to $myVar
    $myVar = 42;
    $b = function() use ($myVar)
    {
        // $b can read $myVar
        // no one else can
        return $myVar;      
    };
    return $b;
}

  // get $b
$test = a();
  // use $b
echo $test();
?>

5.3.0, a b, :

. :

function a()
{
    // ...
    // Write the variable that
    // only this function can write to
    $thisVar = 1;
    b($thisVar);
    //...
}

function b($myVar)
{
    // ...
    // Do stuff w $myVar, a copy of $thisVar
    // Changing $myVar has no effect on $thisVar
    //
}
+1

? . ( Reflection, ).

/, ( API ), . , .. .. , , . "", , " " - .

+1

Source: https://habr.com/ru/post/1764662/


All Articles