首页 > 解决方案 > PHP:阻止在类外创建实例变量

问题描述

在下面给定的 PHP 类中,我知道 $test 将无法从此类外部访问。

class Resource {
    private $test;
    public function __construct() {
       echo "in init";
       $test = "new val";
    }
}

但是我们将能够定义新的实例变量,如下所示。有什么诀窍可以阻止这种情况吗?

$r = new Resource();
$r->val = "value"; 

标签: phpinstance-variables

解决方案


例如,使用魔术方法(namly __set),您可以告诉类“如果此处未设置,请忽略它”;

<?php

class Resource {
    private $test;
    public function __construct() {
       echo "in init";
       $this->test = "new val";
    }

    public function __set($name, $val)
    {
        // If this variable is in the class, we want to be able to set it
        if (isset($this->{$name})
        {
            $this->{$name} = $val;
        }
        else
        {
            // Do nothing, add an error, anything really
        }
    }
}

$resource = new Resource();
$resource->foo = "bar";
echo $resource->foo; // Will print nothing

供参考,请参阅指南


推荐阅读