1

这是我的课程代码:

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;

谢谢你的帮助。

4

5 回答 5

2

你混淆了很多概念。

首先,您必须创建一个新的 class 对象myClass

$nCls = new myClass();

然后,您可以调用该类的成员函数(方法):

$nCls->result();

result()中,您只需使用以下方法调用其他方法$this

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

但请注意,这没有任何作用。该变量$myvar是本地的,而不是类属性。我建议您阅读面向对象的编程,尤其是面向对象的 PHP

于 2012-11-20T09:51:38.260 回答
2
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();

您可以这样做,但这不是一个好习惯。

于 2012-11-20T09:55:42.387 回答
1

问题是范围,您不能在另一个函数中调用变量,为类定义一个属性并从函数中设置它,然后使用以下命令检索该属性result()

class myClass
{
   public $myvar;

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

   public function result()
   {
      echo $this->myvar;
   }
}
于 2012-11-20T09:49:03.597 回答
1

问题是您$myvar 在 method 范围内声明myFunc()。这意味着它在该方法之外不可见。改为将其声明为类成员:

class myClass
{

   private $myvar;

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

   public function result()
   {
      echo myClass::myFunc()->$myvar;
   }
}
于 2012-11-20T09:49:20.443 回答
1
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";
    }

}
于 2013-10-23T11:36:20.050 回答