我想在我的model.php文件中访问我的变量$ hello,我是怎么做的?
paper.remove()
class {
public function hello() {
$hello = "Hello world";
}
}
我想获得变量$ hello ...
答案 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();