search
HomeBackend DevelopmentPHP TutorialSeveral things to note when using PHP constants_PHP Tutorial

为什么要谨慎使用PHP中的常量?

Zend Framework文档中写道:常量包含数字字母字符和下划线,数字允许作为常量名。 常量名的所有字母必须大写。类常量必须通过 "const" 定义为类的成员,强烈不鼓励使用 "define" 定义的全局常量。

作为PHP的官方框架,为什么会有这样的要求?

让我们一起分析一下吧。

1. define容易产生意想不到的错误

PHP常量是定义后就不能修改和再次赋值。但是如果再次赋值会怎么样?

<?php
  define('C', 12345);
  define('C', 123);
?>

这段代码会报个notice错误。带来的后果是:在你定义之前,其它人要是定义了同名的常量,你可能真的不知道里面究竟是什么值。

2. 如何判断PHP常量是否被定义?判断方法易写错

<?php
  define('C', 12345);
  // 错误方法1,经常犯
  if (isset(C)){……}
  // 错误方法2,经常犯
 if (defined(C)){……}
  // 正确方法
  if (defined('C')){……}
?>

3. 执行效率低

<?php
    define('FORUM_THEME',$forum['theme']); 
    $this->display('/'.FORUM_THEME.'@Public:login');  
    //  系统会从整个执行流程中查找FORUM_THEME
?>

因为php处理常量的时候要进行多次查找,所以效率低。

总结:PHP常量的问题,在于PHP处理常量的方法过于宽松导致的,如果能够严格一些,就会避免很多的问题。在实际过程,能用变量就不要用常量,因为变量的效率高使用更加方便。

因此若非要使用常量或者类变量,可使用以下方法:

<?php
  class foo {
    const WEBSITE = "www.zhuyinghao.com";
    protected $_forum_theme;
    function name()
    {
        echo WEBSITE;
        $this->_forum_theme = $forum['theme'];
    }
    function displace() 
    {
       echo $this->_forum_theme;
    }
  }
?>

类名和函数名相同时的作用

在PHP 4中,类的构造函数需要和类名相同,子类的构造函数名与子类名相同,在子类里父类的构造函数不会自动执行。要在子类里执行父类的构造函数,必须执行类似以下语句:

$this->[父类的构造函数名()]

在 PHP 5.0 以上版本里,统一使用construct()作为构造函数,但仍兼容了 4.0 版本的构造函数的定义规则。如果同时定义了4.0的构造函数和 construct()函数,则construct() 函数优先。

用PHP EOL来替换/r/n进行换行

写程序时会经常用到换行,用PHP内置常量PHP_EOL来进行换行。

一个小小的换行,在不同的平台有着不同的实现。在unix世界换行就用\n来代替,但是windows为了体现他的不同,就用\r\n,更有意思的是在mac中用\r。因此unix系列用 \n,windows系列用 \r\n,mac用 \r。

因此系统会根据平台系统的不同,转换成不同的换行。如果要在浏览器中换行,就要使用PHP_EOL变量进行换行

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752544.htmlTechArticle为什么要谨慎使用PHP中的常量? Zend Framework文档中写道:常量包含数字字母字符和下划线,数字允许作为常量名。 常量名的所有字母必须大...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment