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

后端 未结 3 1654
心在旅途
心在旅途 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:48

    You cannot use hyphens (dashes) in PHP class properties. PHP variable names, class properties, function names and method names must begin with a letter or underscore ([A-Za-z_]) and may be followed by any number of digits ([0-9]).

    You can get around this limitation by using member overloading:

    class foo
    {
        private $_data = array(
            'some-foo' => 4,
        );
    
        public function __get($name) {
            if (isset($this->_data[$name])) {
                return $this->_data[$name];
            }
    
            return NULL;
        }
    
        public function __set($name, $value) {
            $this->_data[$name] = $value;
        }
    }
    
    $foo = new foo();
    var_dump($foo->{'some-foo'});
    $foo->{'another-var'} = 10;
    var_dump($foo->{'another-var'});
    

    However, I would heavily discourage this method as it is very intensive and just generally a bad way to program. Variables and members with dashes are not common in either PHP or .NET as has been pointed out.

提交回复
热议问题