如何使用 {'属性名称-like-this'} 声明动态 PHP 类



我正在将应用程序从.NET重写为PHP。我需要创建这样的类:

class myClass
{
    public ${'property-name-with-minus-signs'} = 5;
    public {'i-have-a-lot-of-this'} = 5; //tried with "$" and without
}

但它不起作用。我不想用这样的东西:

$myClass = new stdClass();
$myClass->{'blah-blah'};

因为我有很多这样的代码。

几天后编辑:我正在编写使用SOAP的应用程序。这些新奇的名字在API中使用,我不得不与之交流。

在PHP类属性中不能使用连字符(破折号)。PHP变量名、类属性、函数名和方法名必须以字母或下划线([A-Za-z_])开头,后面可以跟任意数字([0-9])

你可以通过使用成员重载绕过这个限制:

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'});

然而,我强烈反对这种方法,因为它非常密集,而且通常是一种糟糕的编程方式。如前所述,带破折号的变量和成员在PHP或.NET中并不常见。

我使用了这样的代码:

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;   
    }
}

您可以使用__get魔术方法来实现这一点,尽管这可能会变得不方便,具体取决于目的:

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.");
    }
}

然而,考虑到大多数.NET语言的标识符中都不允许使用-,而且您可能正在使用类似于__get的索引器,它应该可以很好地满足您的目的。

最新更新