dqyz48470 2017-03-18 17:45
浏览 48
已采纳

不允许动态创建公共属性

Let's start with simple PHP code:

<?php

class Test 
{
}

$test = new Test();
$test->x = 20;
echo $test->x;

The problem here is this code works without any problem (tested in PHP 7.1, probably in some previous versions it works also without any problems).

The problem I see here that when using code like this, it's very easy to write code that is very hard to analyse and can contain some hidden bugs.

The question: is there any way to don't allow to dynamically create properties for objects especially outside of the class?

For custom class like this the solution that could be used is creating custom __set method that will creating not declared properties like this:

public function __set($property, $value)
{
    if (!property_exists($this, $property)) {
        throw new Exception("Property {$property} does not exit");

    }
    $this->$property = $value;
}

but it obviously doesn't solve problem of protected/private properties - property_exists would return true also for protected and private properties (need to use Reflection for this).

  • 写回答

1条回答 默认 最新

  • doujiao7679 2017-03-18 17:57
    关注
    <?php
    ini_set("display_errors", 1);
    class Test 
    {
        protected $name="ss";
        public function __set($property, $value)
        {
            //Checked for undefined properties
            if(!isset(get_object_vars($this)[$property]))
            {
                 throw new Exception("Property {$property} does not exit");            
            }
            //Checking for public properties
            $prop = new ReflectionProperty($this, "name");
            if(!$prop->isPublic())
            {
                throw new Exception("Property {$property} does not exit");            
            }
            //Checking for non-existing properties
            if (!property_exists($this, $property)) 
            {
                throw new Exception("Property {$property} does not exit");
            }
            $this->$property = $value;
        }
    }
    
    $test = new Test();
    $test->x = 20;
    echo $test->x;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制