PHP如何在另一个类的函数中传递类的实例?

时间:2014-07-26 14:05:57

标签: php class

的index.php

include('./class1.php');
include('./class2.php');

$Func = new function_test();
$Func->testfuncton1();

class1.php

class controller{

  public function test2(){
    echo 'this is test';
  }
}

class2.php

class function_test{

  public $string_row;

  public function __construct() {
   $this->string_row = 'TEST code';
  }

  public function testfuncton1(){
    controller::test2();
  }
}

我们希望在课程$string_row中的函数test2()中打印值controller,但我们不知道该怎么做...

请告诉我如何在另一个类的函数中传递该类的实例?

P.S。:我们在班级$string_row中有元素function_test。我们希望在函数test2()中显示其值(在类controller中)。

2 个答案:

答案 0 :(得分:0)

我添加了一些额外的方法来展示所有可能性:

class controller{
  //normal methods, must be called on instances of controller    

  //pass a object of type function_test
  public function testObject($object){
    echo $object->string_row;
  }

  //pass a string 
  public function testString($string){
    echo $string;
  }

  //static method, can be called on the class itself
  public static function staticTest($string){
    echo $string;
  }
}

现在调用方法:

class function_test{

  public $string_row;

  public function __construct() {
   $this->string_row = 'TEST code';
  }

  public function testfuncton1(){
    (new controller())->testObject($this);
    //or
    (new controller())->testString($this->string_row);
    //or call the static one
    controller::staticTest($this->string_row);
  }
}

应该是:$this->string_row 我强烈建议您阅读一本关于面向对象编程的好书。

答案 1 :(得分:0)

好的,你错了: - $this->$string_row = 'TEST code';应为$this->string_row = 'TEST code'; - 同样如前所述,最好使用regular functions而不是objects来呼叫classes

所以,controller::test2();最好写成

$cn = new controller();
$cn->test2();

我认为从设计的角度来看,最好在类控制器中实例化一个function_test的对象,并使用它而不是传递它。

class controller{

  public function test2(){
    echo 'this is test';
     //since we call the constructor of function_test,
     //this will assign value to string_row
    $ft = new function_test();

    // since string_row is a public property, 
    // you can directly echo it.
    echo $ft->string_row;
  }
}