【问题标题】:Can the constants be defined inside a model file of a framework in PHP?可以在 PHP 框架的模型文件中定义常量吗?
【发布时间】:2015-06-04 13:30:06
【问题描述】:

我正在使用 PHPFox 框架。我必须定义两个常量,它们只能由该模型类文件中存在的两个函数使用。那么我可以在这个模型类文件的开头定义常量还是会导致任何问题或者它是否违反编码标准?

请在这方面帮助我。

以下是此模型类文件中的一种方法。

我想写以下代码:

<?php
/**
 * [PHPFOX_HEADER]
 */
/*header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');*/

defined('PHPFOX') or exit('NO DICE!');

/**
 * 
 * 
 * @copyright       [PHPFOX_COPYRIGHT]
 * @author          Raymond Benc
 * @package         Phpfox_Service
 * @version         $Id: service.class.php 67 2009-01-20 11:32:45Z Raymond_Benc $
 */
class Notification_Service_Process extends Phpfox_Service 
{
/**
     * Class constructor
     */ 
    public function __construct()
    {   
        $this->_sTable = Phpfox::getT('notification');
    }

    public function add($sType, $iItemId, $iOwnerUserId, $iSenderUserId = null)
    {
        if ($iOwnerUserId == Phpfox::getUserId()&&$iSenderUserId==null)
        {
            return true;
        }

        if ($sPlugin = Phpfox_Plugin::get('notification.service_process_add'))
        {
            eval($sPlugin);
        }       

        if (isset($bDoNotInsert) || defined('SKIP_NOTIFICATION'))
        {
            return true;
        }

        $aInsert = array(
            'type_id' => $sType,
            'item_id' => $iItemId,
            'user_id' => $iOwnerUserId, 
            'owner_user_id' => ($iSenderUserId === null ? Phpfox::getUserId() : $iSenderUserId),
            'time_stamp' => PHPFOX_TIME     
        );  
        $this->database()->insert($this->_sTable, $aInsert);    

        return true;
    }
}
?>  

我想定义以下两个常量:

define('PW_AUTH', '8s4QpeUyLX9BodAy');
define('PW_APPLICATION', 'R8T89-29690');

提前致谢。

【问题讨论】:

    标签: php model-view-controller model constants phpfox


    【解决方案1】:

    Set them as constants in the class.

    来自 PHP 手册:

    <?php
    class MyClass
    {
        const CONSTANT = 'constant value';
    
        function showConstant() {
            echo  self::CONSTANT . "\n";
        }
    }
    

    【讨论】:

    • 不能在类定义之前设置吗?
    • 变量 you define 用于整个应用程序,而 constants 类仅在该类(和子类)中使用。既然您说“将仅由该模型类文件中存在的两个函数使用”,您想使用后者,而不是前者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多