Yii全局函数用法示例

本文实例讲述了Yii全局函数用法分享给大家供大家参考,具体如下:

由于YII致力于完美的整合第三方库,它并没有定义任何全局函数。yii中的每一个应用都需要全类别和对象范围。

例如,user;Yii::app()->params['name'];等等。我们可以自行设定全局函数,使得代码看起来更加简洁易用。

我们可以保存在globals.PHP在protected/config目录下。然后,在入口脚本index.PHP中,定义如下内容

rush:PHP;"> $globals=dirname(__FILE__).'/protected/config/globals.PHP'; ... require_once($yii); require_once($globals);

现在我们可以在应用的任何地方使用我们的全局函数,例如可以使用user()代替Yii::app()->user。注:一个可重用的组件,请不要组件中使用全局函数,在不同的应用配置中,可能导致无法使用。同时,也应注意与第三方库的冲突,可考虑对每个函数加上自己的前缀,已做区分,例如框架核心均已C为前缀。

下面是代码包含最常用的一些快捷功能。如还需其他,请自行添加

clientScript */ function cs() { // You Could also call the client script instance via Yii::app()->clientScript // But this is faster return Yii: :app() - >getClientScript(); } /** * This is the shortcut to Yii::app()->user. */ function user() { return Yii: :app() - >getUser(); } /** * This is the shortcut to Yii::app()->createUrl() */ function url($route,$params = array(),$ampersand = '&') { return Yii: :app() - >createUrl($route,$params,$ampersand); } /** * This is the shortcut to CHtml::encode */ function h($text) { return htmlspecialchars($text,ENT_QUOTES,Yii: :app() - >charset); } /** * This is the shortcut to CHtml::link() */ function l($text,$url = '#',$htmlOptions = array()) { return CHtml: :link($text,$url,$htmlOptions); } /** * This is the shortcut to Yii::t() with default category = 'stay' */ function t($message,$category = 'stay',$source = null,$language = null) { return Yii: :t($category,$message,$source,$language); } /** * This is the shortcut to Yii::app()->request->baseUrl * If the parameter is given,it will be returned and prefixed with the app baseUrl. */ function bu($url = null) { static $baseUrl; if ($baseUrl === null) $baseUrl = Yii: :app() - >getRequest() - >getBaseUrl(); return $url === null ? $baseUrl: $baseUrl.'/'.ltrim($url,'/'); } /** * Returns the named application parameter. * This is the shortcut to Yii::app()->params[$name]. */ function param($name) { return Yii: :app() - >params[$name]; } /** * A useful one that I use in development is the following * which dumps the target with Syntax highlighting on by default */ function dump($target) { return CVarDumper: :dump($target,10,true); }

更多关于Yii相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《PHP常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


服务器优化必备:深入了解PHP8底层开发原理
Golang的网络编程:如何快速构建高性能的网络应用?
Golang和其他编程语言的对比:为什么它的开发效率更高?
PHP8底层开发原理揭秘:如何利用新特性创建出色的Web应用
将字符重新排列以形成回文(如果可能)在C++中
掌握PHP8底层开发原理和新特性:创建高效可扩展的应用程序
服务器性能优化必学:掌握PHP8底层开发原理
PHP8新特性和底层开发原理详解:优化应用性能的终极指南
将 C/C++ 代码转换为汇编语言
深入研究PHP8底层开发原理:创建高效可扩展的应用程序
C++程序查找法向量和迹
PHP8底层开发原理实战指南:提升服务器效能
重排数组,使得当 i 为偶数时,arr[i] >= arr[j],当 i 为奇数时,arr[i] <= arr[j],其中 j < i,使用 C++ 语言实现
Golang的垃圾回收:为什么它可以减少开发人员的负担?
C++程序:将一个数组的所有元素复制到另一个数组中
Golang:构建智能系统的基石
为什么AI开发者应该关注Golang?
在C和C++中,逗号(comma)的用法是用来分隔表达式或语句
PHP8底层开发原理解析及新特性应用实例
利用PHP8底层开发原理解析新特性:如何构建出色的Web应用