2016-09-30 43 views
-1

我有一個查詢返回的數組。我想數組是一個對象,所以我寫:將數組轉換爲對象並調用它的函數

$object = (object)($array); 

我想調用$對象的方法,但是當我啓動:

$object->getUsername(); 

我得到這個錯誤:

Attempted to call method "getName" on class "stdClass". 

如何訪問對象的數據?

這是我的課的一部分:

class User implements AdvancedUserInterface, \Serializable 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    * @ORM\OneToMany(targetEntity="UserLicense", mappedBy="user_id") 
    */ 
    private $id; 

    /** 
    * @ORM\ManyToOne(targetEntity="Currency", inversedBy="users") 
    * @ORM\JoinColumn(name="id_currency", referencedColumnName="id") 
    */ 
    protected $currency; 

    /** 
    * @ORM\Column(type="string", length=25, unique=true) 
    */ 
    private $username; 

    /** 
    * @ORM\Column(type="string", length=64) 
    */ 
    private $password; 

這是我通過主義使用查詢:

$em = $this->getDoctrine()->getManager(); 
    $currency = $em->getRepository('UserBundle\Entity\User')->findBy(array('email' => $userMail)); 
+0

@RyanVincent編輯! –

+0

@RyanVincent是的,通過教條。添加 –

+0

'警告:get_class()期望參數1是對象,數組給予' –

回答

1

當你鑄造數組對象,它創造stdClass實例。

這是一個包含所有公共屬性的簡單對象。

所以,簡單地訪問他們像這樣:

$object->name; 

這裏有一個工作示例:https://3v4l.org/Ui9uY

+0

我得到這個:'注意:未定義的屬性:stdClass :: $ name' –

+2

數組是否有'name'索引? –

+0

也許你可以在你的數組上做一個var_dump(),這樣我們可以看到裏面是什麼? – KatharaDarko

0

爲了這個工作,你必須變換陣列成有,你需要方法的對象。

當你使用(object) $array它將分配類stdClass這是一個在PHP中沒有方法的泛型類。所以你不會在那裏有你需要的方法。

您應該創建一個具有所需簽名的類,並且在實例化該對象時將該數組傳遞給構造函數,並將其保存爲屬性或每個對key=>value爲具有相應值的屬性。

例如:

$userData = ['name' => 'John', 'email' => '[email protected]']; 

class User 
{ 
    property $name; 
    property $email; 

    public function __construct(array $userData) 
    { 
     // here you'll need some data validation but is not case for this example 
     $this->name = $userData['name']; 
     $this->email = $userData['email']; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 

    public function getEmail() 
    { 
     return $this->email; 
    } 
} 

$user = new User($userData); 

echo $user->getName(); 

這種方式在應用程序中的每個對象都會有一個特定的類型,它會幫助你的時間。另外,您可以使用該對象的接口。