2015-09-09 61 views
1

嘿,我在PHP一個類實例化和使用方法填充一個對象

測試一些OPP原則,我創建了一個類與需要兩個參數的方法。

當我實例化一個類,並調用參數數據的方法,我什麼也得不到。

<?php 

class example 
{ 
    public $request; 

    public function test($uprn, $sourceChannel) 
    { 
     $this->request = new stdClass(); 
     $this->request->uprn = $uprn; 
     $this->request->sourceChannel = $sourceChannel; 

    } 

} 

$test = new example(); 
$test->test('1', '2'); 

var_dump($test);die; 

所有我在瀏覽器中得到的是這樣的一個空對象:

object(example)#1 (0) { } 

但我希望這樣的:

object(example)#1 (2) { ["uprn"]=> string(1) "1" ["sourceChannel"]=> string(1) "2" } 

任何想法,我錯了...... ?

+0

也許你想用'$ this'而不是'$ request' – Rizier123

+0

你沒有給實例分配任何東西。 '$ request'只存在於'test'方法的範圍內。 –

+0

'$ this-> request',不是簡單的'$ request' ....後者是局部作用域的函數,前者是一個對象屬性 –

回答

1
> stdClass is PHP's generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out). It is useful for anonymous objects, dynamic properties. 

    You can get desired output just like this. 

    $request = new stdClass(); 
    $request->uprn = $var1; 
    $request->sourceChannel = $var2; 
    var_dump($request);die; 


    please go through this link to understand Generic empty class(stdClass). 
    http://krisjordan.com/dynamic-properties-in-php-with-stdclass 

    In PHP OOPS you can get the output as given below 
    class example 
    { 
     var $uprn,$sourceChannel; 

     public function test($uprn, $sourceChannel) 
     {   
      $this->uprn = $uprn; 
      $this->sourceChannel = $sourceChannel; 
     }} 

    $test = new example(); 
    $test->test('1', '2'); 
    var_dump($test);die; 


    To understand much better go through this 
    http://php.net/manual/en/language.oop5.php 

    Thanks 
相關問題