【问题标题】:How to declare dynamic PHP class with {'property-names-like-this'} [duplicate]如何使用 {'property-names-like-this'} 声明动态 PHP 类
【发布时间】:2012-02-17 03:03:20
【问题描述】:

我正在将应用程序从 .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。

【问题讨论】:

  • 为什么需要花括号?只做public $property-name-with-minus-signs = 5有什么问题?
  • @Jam Uhm...它不起作用? :)
  • @JamWaffles:也许……语法错误? :)
  • @Kamil 为什么你首先需要带有破折号的属性? PHP 不是 .NET,变量或属性名称中的破折号在 PHP 世界中并不常见(猜猜为什么;因为它们不起作用)。 CamelCasing 是编写这些的常用方法。
  • @deceze:我认为您也不能在 任何 .NET 语言的标识符中使用破折号。

标签: php class dynamic


【解决方案1】:

您不能在 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 中并不常见。

【讨论】:

  • 正如我所写 - 它们工作(作为动态属性,但我需要克隆该类,并且我需要克隆类中的默认值。
  • @Kamil 在构造函数中设置默认值。或者我有个好主意!不要使用包含连字符的标识符! :)
【解决方案2】:

我使用了这样的代码:

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】:

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

    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 语言的标识符中都不允许使用 -s,并且您可能正在使用类似于 __get 的索引器,它应该可以很好地满足您的目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多