2017-10-08 49 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 
相关问题