Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

 class Foo 
{
    public $var ;

    function __construct($value) 
    {
         $this->var = $value ;
    }
}
$myFoo = new Foo('hello');
echo $myFoo->var . '<br>' ; // output : hello
// Question : how  can I prevent another programer from accidentaly doing the following
$myFoo = 4 ;
echo $myFoo ; // output : 4

my question is in the comment // Question :...

I would like my coworkers being able to assign values to $myFoo use only $myFoo->var (or whatever public mutators are available in the class Foo)

thank you

EDIT : with all respect to the users who claim it is not possible, SPL_Types PECL extention was able to achieve that (to a certain degree) see e.g http://php.net/manual/en/class.splint.php or http://blog.felixdv.com/2008/01/09/spl_types-in-php-and-strong-typing/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot do this in any weakly typed language. If you have functions that take this variable as an argument, you can use type hinting in PHP, but otherwise you cannot prevent people from re-assigning their variables.

This is true to an extent even for strongly typed languages. If a programmer creates two instances of a class, there is no mechanism to prevent them from assigning a different instance to a variable of the same type.

The only way this can happen is if the programmer explicitly uses constants instead of variables (such as using things like final in Java, or val in Scala, etc), but, either way, you have no control over it in any language.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...