PHP:在课堂另一个函数中调用变量(PHP : call variable from another

2019-08-02 23:55发布

这是我的类代码:

class myClass
{

   public function myFunc()
   {
      $myvar   =  'Test str';
   }

   public function result()
   {
      echo myClass::myFunc()->$myvar;
   }
}

我用这样的:

   $nCls = new myClass;
   $nCls->result();

要显示Test str形式myFunc()表示,但没有。 我认为这个问题是:

echo myClass::myFunc()->$myvar;

谢谢你的帮助。

Answer 1:

问题是,你声明$myvar 只有在方法的范围myFunc() 这意味着它不是法外可见。 声明为类成员,而不是:

class myClass
{

   private $myvar;

   public function myFunc()
   {
      $this->myvar   =  'Test str';
   }

   public function result()
   {
      echo myClass::myFunc()->$myvar;
   }
}


Answer 2:

你是相当多的概念混淆了。

首先,你必须创建类的新对象myClass

$nCls = new myClass();

然后,你可以调用这个类的成员函数(方法):

$nCls->result();

result()你只需要调用使用其他方法$this

public function result()
{
   echo $this->myFunc();
}

不过,请注意,这什么也不做。 变量$myvar是本地的,而不是一类属性。 我劝你读了面向对象编程和面向对象的PHP尤其如此。



Answer 3:

class myClass {
    public $myvar;
    public function myFunc() {
        $this->myvar = 'Test str';
        return $this;
    }

    public function result() {
        echo $this->myFunc()->myvar;
    }
}

$nCls = new myClass;
$nCls->result();

你可以这样做,但是这是不是一个好的做法。



Answer 4:

问题的范围,你不能叫一个变量另一个函数内,定义一个属性为类和功能设置,然后用检索的属性result()

class myClass
{
   public $myvar;

   public function myFunc()
   {
      $this->myvar   =  'Test str';
   }

   public function result()
   {
      echo $this->myvar;
   }
}


Answer 5:

include "views.php";
class Controller extends views{

    function index(){
        $this->head();  
        $this->home();
    }
    function privacy(){
        $this->head();
        $this->privc();
    }
    function about(){
        $this->head();
        $this->abt();
    }
    function address(){
        $this->head();
        $this->add();
    }
}
$obj=new Controller();

if(isset($_GET['fun'])){
    $obj->$_GET['fun']();
}
else{
    $obj->index();  
}



   This is views.php code


   class views{
    function head(){
        include "views/header.php";
        echo "<br>this is header";  
    }
    function abt(){
        include "views/about.php";
        echo "<br>This is about us page";   
    }
    function home(){
        include "views/home.php";
        echo "<br>This is Home page";
    }
    function privc(){
        include "views/privacy.php";
        echo "<br>This is privacy page";
    }
    function add(){
        include "views/address.php";
        echo "<br>This is address page";
    }

}


文章来源: PHP : call variable from another function in class
标签: php class