How to declare dynamic PHP class with {'property-names-like-this'}

后端 未结 3 1695
心在旅途
心在旅途 2021-01-14 15:58

Im rewriting application from .NET to PHP. I need to create class like this:

class myClass
{
    public ${\'property-name-with-minus-signs\'} = 5;
    public         


        
3条回答
  •  忘掉有多难
    2021-01-14 16:35

    You can use the __get magic method to achieve this, although it may become inconvenient, depending on the purpose:

    class MyClass {
        private $properties = array(
            'property-name-with-minus-signs' => 5
        );
    
        public function __get($prop) {
            if(isset($this->properties[$prop])) {
                return $this->properties[$prop];
            }
    
            throw new Exception("Property $prop does not exist.");
        }
    }
    

    It should work well for your purposes, however, considering that -s aren't allowed in identifiers in most .NET languages anyway and you're probably using an indexer, which is analogous to __get.

提交回复
热议问题