2017-10-08 91 views
0

在我的課堂我想設置一個變量的值比__construct()OOP PHP在一個函數設置變量的值,並從另一個功能

以外的功能得到但我需要在另一個函數變量的值。

這是我試過的,但沒有正常工作。

I expect to print蓋蒂圖片社but i get nothing :(

<?php 

class MyClass{ 
    public $var; 

    public function __construct(){ 
     $this->var; 
    } 

    public function setval(){ 
     $this->var = 'getty Images'; 
    } 

    public function printval(){ 
     echo $this->var; 
    } 
} 

$test = new MyClass(); 
$test->printval(); 
+0

你有什麼期望?你有什麼? –

+0

我希望打印'getty images',但是我什麼都沒有得到:( – Hudai

+1

爲什麼你打印的東西,因爲你從來沒有把任何東西放在'$ this-> var'中? – axiac

回答

5

你的構造函數什麼也不做,你需要調用的方法爲它做點什麼。

class MyClass{ 
    private $var; 

    public function __construct() { 
     // When the class is called, run the setVal() method 
     $this->setval('getty Images'); 
    } 

    public function setval($val) { 
     $this->var = $val; 
    } 

    public function printval() { 
     echo $this->var; 
    } 
} 

$test = new MyClass(); 
$test->printval(); // Prints getty Images 
+0

這就好像,和設置值一樣這個構造函數,除了它更多的是間接的,爲什麼簡單的時候你可以混淆每個人的地獄?) –

+0

使用setter不是更好嗎? OP已經有一個設置該值的方法,所以爲什麼不使用它。你的觀點是直接在構造函數中使用'$ this-> var ='getty Images';'? –

+1

這不是一個setter。 setter將是'function setValue($ v){$ this-> value = $ v; }'。不,注射器注射一般不會比構造注射更好。這有點爭論,但我從來沒有使用過它,因爲它大多隻會導致問題的發生。在這個特定的情況下,沒有區別,因爲**值不會傳遞給setter函數**。這是死代碼。所以是的,我的意思是這個函數應該在構造函數中重構,因爲它實際上並不在類的外部使用,而是在構造函數中使用。 –

1

您需要調用setval()方法實際設置一個值。

嘗試:

<?php 

$test = new MyClass(); 
$test->setval(); 
$test->printval(); 

如果您是具有固定值,設定變量在__construct幸福()將正常工作,我會推薦這種方法。

然而,如果你願意,你可以調整你的SETVAL方法的動態值acccept參數和傳遞的參數保存到你的對象渲染爲printval()調用的一部分。

0

你首先需要在打印

<?php 

class MyClass{ 
    public $var; 

    public function setval(){ 
     $this->var = 'getty Images'; 
    } 

    public function printval(){ 
     echo $this->var; 
    } 
} 

$test = new MyClass(); 
$test->setval(); 
$test->printval(); 
?> 

輸出前值設置爲您的變量:

getty Images 
相關問題