我将应用程序从.NET重写为PHP.我需要创建这样的类:
class myClass
{
public ${'property-name-with-minus-signs'} = 5;
public {'i-have-a-lot-of-this'} = 5; //tried with "$" and without
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我不想使用这样的东西:
$myClass = new stdClass();
$myClass->{'blah-blah'};
Run Code Online (Sandbox Code Playgroud)
因为我在代码中有很多这个.
几天后编辑:我正在编写使用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'});
Run Code Online (Sandbox Code Playgroud)
但是,我会大力劝阻这种方法,因为它非常密集,通常只是一种糟糕的编程方式.变量和带破折号的成员在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;
}
}
Run Code Online (Sandbox Code Playgroud)