开发者

Is there a better way to block property overloading?

开发者 https://www.devze.com 2023-01-30 05:47 出处:网络
<?php class Item { public function __set($name, $value){ throw new Exception(\'Overloading is forbidden.\');
<?php
class Item {
 public function __set($name, $value){
  throw new Exception('Overloading is forbidden.');
 }

 p开发者_运维问答ublic function __get($name){
  throw new Exception('Overloading is forbidden.');
 }
}

I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null.


From your comment:

I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null.

If you want to make sure you have set all required object properties, consider making them required arguments to the constructor, e.g.

class Item
{
    public function __construct($required, $alsoRequired, $moreRequired)
    {
        // assign to corresponding properties
    }
}

This way you can be sure the object is in valid state.

If you cannot set them at object creation, consider adding a validator method to your object. Call this method before doing any critical things with your object to make sure all required properties are set. This would be a much more useful addition to your API than implementing a typo safeguard.

In addition, you should not have an issue with this if you use proper setters. Access your object through an interface instead of assigning properties directly. If you mistype a method name, PHP will tell you (unless you implemented __call).

On a sidenote, __get and __set are not lazy replacements for proper Getters and Setters. They are interceptors that will be triggered when trying to access a non accessible property. This is much more related to error handling. Also note that they are much slower than proper Getter and Setter.


Just using the constructor will not solve the problem. The problem he describes is very common and throwing an exception if __get or __set are called is a nice idea. If you want to, you can make those final but I see no reason why you should do this. Only classes that require dynamic propertys will override the methods. The only improvement I can suggest is enclosing the method definitions in //DEBUG and /// When you are finished debugging you can then easily run a replace(//*DEBUG with /*DEBUG) on all your code files and comment out __get and __set


Using http://php.net/manual/en/function.get-class-vars.php you can check for existence of the variable and for example throw exception when fails

0

精彩评论

暂无评论...
验证码 换一张
取 消