2013-05-04 27 views
4

有一種神奇的方法__toString,如果一個對象在字符串上下文中使用或鑄造成這樣,如何將object中的特殊值返回給數組?

<?php 

class Foo { 
    public function __toString() { 
     return 'bar'; 
    } 
} 

echo (string) new Foo(); // return 'bar'; 

是否有當一個對象被castend到(array)將被觸發類似的功能?

+1

你怎麼可能會施放一個對象到一個數組不知道它的類型(更確切地說,如果它不知道是'stdClass')?如果你知道它的類型,爲什麼它需要鑄造? – Jon 2013-05-04 18:52:32

+0

我知道這是一個對象。值被傳遞的層不使用Object功能,並且僅限於數組。現在我通過簡單地提供一個自定義方法「flatten」來做到這一點。只是出於好奇而問這個問題。 – Gajus 2013-05-04 18:54:46

回答

2

不,但有ArrayAccess接口,它允許您將類用作數組。要獲得循環功能,您需要連接IteratorAggregateIterator。如果你有一個內部數組,你只需要重寫一個方法(它提供了一個ArrayIterator的實例),但前者更容易使用,但後者允許你對迭代進行更細粒度的控制。

例子:

class Messages extends ArrayAccess, IteratorAggregate { 
    private $messages = array(); 

    public function offsetExists($offset) { 
     return array_key_exists($offset, $this->messages); 
    } 

    public function offsetGet($offset) { 
     return $this->messages[$offset]; 
    } 

    public function offsetSet($offset, $value) { 
     $this->messages[$offset] = $value; 
    } 

    public function offsetUnset($offset) { 
     unset($this->messages[$offset]); 
    } 

    public function getIterator() { 
     return new ArrayIterator($this->messages); 
    } 
} 

$messages = new Messages(); 
$messages[0] = 'abc'; 
echo $messages[0]; // 'abc' 

foreach($messages as $message) { echo $message; } // 'abc' 
+0

謝謝,雖然我有興趣將性能值轉換爲數組。 – Gajus 2013-05-04 18:52:04

+0

@GajusKuizinas如何將數組轉換爲數組有助於性能? – 2013-05-04 18:57:19

+0

當然,訪問,迭代等對象比在裸露陣列上執行相同的操作要慢(且耗費更多的內存)。 – Gajus 2013-05-04 19:03:21

2

這可能不是正是你可能預期的,因爲你所期望的不作爲PHP(不幸)的語言功能,但這裏談到一個衆所周知的解決方法:

使用get_object_vars()此:

$f = new Foo(); 
var_dump(get_object_vars($f)); 

它將返回屬性名稱作爲索引和他們的價值關聯數組。檢查這個例子:

class Foo { 

    public $bar = 'hello world'; 

    // even protected and private members will get exported: 
    protected $test = 'I\'m protected'; 
    private $test2 = 'I\'m private'; 


    public function toArray() { 
     return get_object_vars($this); 
    } 

} 

$f = new Foo(); 
var_dump($f->toArray()); 

輸出:

array(2) { 
    'bar' => 
    string(11) "hello world" 
    'test' => 
    string(13) "I'm protected" 
    'test2' => 
    string(13) "I'm private" 
} 
相關問題