2010-12-06 103 views
3

在java中,我們有Object類型可用於轉換爲特定的類類型。 我們如何在PHP中做到這一點?什麼是Java的對象類的PHP等效物

問候, 大額牛

+0

不知道你需要做的,但看看這個是什麼:http://php.net/manual/en/language.oop5.php – baloo 2010-12-06 11:02:38

回答

4

在PHP中的通用對象是stdClass實例。但它不是基類,這意味着類不會繼承它,除非在類聲明中指定了extends stdClass

在PHP中輸入(object)會產生stdClass。例如:

$a = array('foo' => 'bar'); 
$o = (object) $a; 
var_dump($o instanceof stdClass); // bool(true) 
var_dump($o->foo); // string(3) "bar" 

在PHP中,沒有上傳和向下轉換的概念。你可以爲超類或接口輸入提示,但這就是它。一個對象總是被認爲是你構造它的任何類的一個實例,例如與new

-1

由於PHP沒有類型聲明,因此不需要全局基類。沒有什麼可做的:只聲明變量並使用它們。

0

Ciaran answer is helpful,

儘管什麼其他兩個答案 說,stdClass的是不適合的PHP對象的基類 。這可以證明 相當容易:

class Foo{} 
$foo = new Foo(); 
echo ($foo instanceof stdClass)?'Yes':'No'; 

它輸出「N」 stdClass的是不是隻是一個 通用的「空」時 鑄造其他類型對象的二手類。 我 不相信有一個 基本對象的PHP

2

一個概念,這將是stdClass(這是不是一個基類FTM)。

請注意,您只能從typecaststdClass而不是任何其他類,例如,這將工作

$obj = (object) array('foo' => 'bar'); 

但不

$observer = (Observer) new Subject; 

引述手冊:

如果對象被轉換爲一個對象,它不被修改。如果任何其他類型的值被轉換爲對象,則會創建stdClass內置類的新實例。如果該值爲NULL,則新實例將爲空。數組轉換爲一個具有按鍵指定屬性的對象,以及相應的值。對於任何其他值,名爲標量的成員變量將包含該值。

好吧,除非你願意使用黑魔法和不可靠的黑客,如給出的:

3

正如有人用PHP和Java經驗,我可以說在php中沒有與Java的對象相當的東西。在Java中,每個對象都會擴展Object類,在php中,您所做的一個類默認不會擴展任何東西。 Java的對象有一些方便的方法,比如toString(),hashCode(),getClass()以及其他一些與php無關的方法。

我喜歡這些在Java中的標準方法,它們非常方便調試和記錄,所以我很想念在PHP中。這就是爲什麼我通常在php中創建自己的基類,並讓每個類都擴展它。然後它變得很容易記錄和調試,你可以只需$ logger-> log($ obj); 它會使用魔法__toString(),至少傾倒關於對象的基本信息。

底線是你可以在php中創建自己的基類,然後讓每個類都擴展它。

我通常的基類:

/** 
* Base class for all custom objects 
* well, not really all, but 
* many of them, especially 
* the String and Array objects 
* 
* @author Dmitri Snytkine 
* 
*/ 
class BaseObject 
{ 

    /** 
    * Get unique hash code for the object 
    * This code uniquely identifies an object, 
    * even if 2 objects are of the same class 
    * and have exactly the same properties, they still 
    * are uniquely identified by php 
    * 
    * @return string 
    */ 
    public function hashCode() 
    { 
     return spl_object_hash($this); 
    } 

    /** 
    * Getter of the class name 
    * @return string the class name of this object 
    */ 
    public function getClass() 
    { 
     return get_class($this); 
    } 

    /** 
    * Outputs the name and uniqe code of this object 
    * @return string 
    */ 
    public function __toString() 
    { 
     return 'object of type: '.$this->getClass().' hashCode: '.$this->hashCode(); 
    } 

} 
相關問題