天天看点

CAKEPHP中调用其它类的方法【续】

大家好,我是Jack.欢迎来到我的博客空间。

本文目标:在当前类中调用其它类中的自己写的方法(Personal Function)。

上次文章说到了如何在一个类加载另一个类的三种方法:App::import(),ClassRegistry::init(),Controller::LoadModel();

相信大家已经可以从其它类调用CakePHP的公用方法,如find('all'),但相信很多人还是不能自如地调用自己写的方法,总是出错。呵呵

看代码:

1)建立测试模型文件 app/models/test.php

<?php

class Test extends AppModel{

public $var = 'Test';

       public $useTable = false;   //不使用数据库,这里为false

       function dis2($string) {

if ($string) {

return "这里提Model的测试方法dis2,  输出结果为: " . $string;

}

else { 

                       echo "这里提Model的测试方法dis2, 无输出结果为"; 

                }

       }

}

?>

2) 建立测试控制器 app/controllers/tests_controller.php

<?php

class TestsController extends AppController{

     var $name = 'Tests';

     var $uses = '';    //不自动加载对应的Model

function dis($string) {

if ($string) {

return "这是控制器中的dis方法,输出结果为:" . $string;

}

else {

                     echo "这是控制器中的dis方法,无输出结果"; 

                }

}

}

?>

3)调用测试代码

<?php

// 从模型类中调用方法

App::import('Model','Test');

$test2 = new  Test();

pr($test2->dis2("11111111111"));

// pr($test2->dis("这是会出错的,无法显示,想想为什么?"));

echo "<br>";

//从控制器类中调用方法

App::import('Controller','Tests');

$test = new TestsController();

pr($test->dis("222222222222"));

// pr($test->dis2("这也是会出错的,无法显示,能相通吗?"));

?>

注意以上从model和controller中分别调用方法的区别!

结论:从model或controller中调用其方法时,要分别对类型加以说明(是model或controller),另调用controller中方法时,类名用复数,初始化类时一定要加上"controller",  这也算是cakephp的特色吧。呵呵

相信通过这两篇文章,各位已经可以畅通无阻地调用任意类中的方法了。呵呵