如何在其他类中获取变量?

时间:2015-12-17 18:26:00

标签: php oop design-patterns

我想在我的model.php文件中访问我的变量$ hello,我是怎么做的?

contollers / Controller.php这样

paper.remove()

模型/ model.php

class {

 public function hello() {

  $hello = "Hello world";

 }

}

我想获得变量$ hello ...

3 个答案:

答案 0 :(得分:2)

为了从一个对象检索数据到另一个对象,您应该创建返回特定数据的方法。

class controller{
    private $hello;

    public function setHello(){
        $this->hello = 'hi';
    }

    public function getHello(){
        return $this->hello;
    }
 }

 class model{

     public function helloWorld(){
         $controller = new controller();
         $controller->setHello();
         $hello = $controller->getHello();

     }

 }

另请注意,通常不会从模型启动控制器,例如以MVC为例。所以基本上在上面的例子中,模型应该是控制器,反之亦然。

答案 1 :(得分:1)

如果您想从获取变量(正如您所说),那么您正在寻找static关键字:

class Controller {
    static $hello = "Hello world";
}

class Model {
    public function helloworld() {
        echo Controller::$hello;
    }
}

$model = new Model();
$model->helloworld();

如果您的意思是“我想创建一个Controller对象,并且Model对象能够从该控制器中读取消息,那么您正在寻找:

class Controller {
    public function hello() {
        return "Hello world";
    }
}

class Model {
    public function helloworld($controller) {
        echo $controller->hello();
    }
}

$controller = new Controller();
$model = new Model();

$model->helloworld($controller);

答案 2 :(得分:1)

你的班级没有名字?

controller.php

<?PHP
class Controller{
    public static function hello () {
        $hello = "Hello World!";
        #when you call a function, you need to say what it must return!
        return $hello;
    }
}
?>

model.php

<?php
class Model extends Controller {
   public static function helloworld() {
     #call the function inside the controller class. class::function();
     $text = Controller::hello();
     #tell what to do, you can use echo or return.
     return $text;
   }
}
?>

index.php

<?PHP
include "controller.php";
include "model.php";
#include everything you need

#use class:function();
echo Model::helloworld();