2012-02-17 42 views
1

我正在從.NET重寫應用程序到PHP。 我需要創建這樣的類:如何用{'property-names-like-this'}聲明動態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。

+2

爲什麼你需要花括號?剛做'public $ property-name-with-minus-signs = 5'有什麼不對? – Bojangles 2012-02-17 03:05:13

+5

@Jam Uhm ...不起作用? :) – deceze 2012-02-17 03:09:25

+2

@JamWaffles:也許...語法錯誤? :) – Ryan 2012-02-17 03:09:34

回答

3

我用這樣的代碼:

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

您不能在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中都不常見。

+1

正如我寫的 - 他們的工作(作爲動態屬性,但我需要克隆該類,我需要在克隆類默認值。) – Kamil 2012-02-17 03:25:07

+0

'$ foo - > {'some-var'}' - yes,'__get' does work 。 – Ryan 2012-02-17 03:43:06

+0

@minitech true,fixed。 – 2012-02-17 04:43:35

1

可以使用__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."); 
    } 
} 

應該爲你的目的很好地工作,但是,考慮到- s的中不允許無論如何,大多數.NET語言都使用標識符,而且您可能正在使用索引器,這與__get類似。

+0

Im PHP noob。我需要嘗試一下。謝謝你minitech。 – Kamil 2012-02-17 03:35:46