我想访问model.php文件中的变量$hello,如何访问??
controllers/controller.php
class {
public function hello() {
$hello = "Hello world";
}
}
型号/型号.php
class {
public function helloworld() {
echo $hello;
}
}
我想得到变量$hello。。。
为了将数据从一个对象检索到另一个对象,您应该创建返回特定数据的方法。
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。所以在上面的例子中,基本上模型应该是控制器,反之亦然。
如果你想从类中获得一个变量(如你所说),那么你正在寻找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);
您的类没有名称?
在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();