问题
Im rewriting application from .NET to PHP. I need to create class like this:
class myClass
{
public ${'property-name-with-minus-signs'} = 5;
public {'i-have-a-lot-of-this'} = 5; //tried with "$" and without
}
But it doesnt work. I dont want to use something like this:
$myClass = new stdClass();
$myClass->{'blah-blah'};
Because i have a lot of this in code.
Edit few days later: i was writing application that uses SOAP. These fancy names are used in API which i had to communicate with.
回答1:
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.
回答2:
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;
}
}
回答3:
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.
来源:https://stackoverflow.com/questions/9322315/how-to-declare-dynamic-php-class-with-property-names-like-this