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

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

    I used code like this:

    class myClass
    {
    
        function __construct() {
    
            // i had to initialize class with some default values
            $this->{'fvalue-string'} = '';
            $this->{'fvalue-int'} = 0;
            $this->{'fvalue-float'} = 0;
            $this->{'fvalue-image'} = 0;
            $this->{'fvalue-datetime'} = 0;   
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题