search
HomeBackend DevelopmentPHP TutorialSeveral things to note when using PHP constants (use constants in PHP with caution), constants php_PHP tutorial

A few things to note when using PHP constants (use constants in PHP with caution), constants php

Why should you use constants in PHP with caution?

Zend Framework documentation writes: Constants contain alphanumeric characters and underscores, and numbers are allowed as constant names. All letters in constant names must be capitalized. Class constants must be defined as members of the class via "const", and the use of "define"-defined global constants is strongly discouraged.

As the official framework of PHP, why is there such a requirement?

Let’s analyze it together.

1. define is prone to unexpected errors

PHP constants cannot be modified or assigned again after they are defined. But what happens if it is assigned again?

<&#63;php
 define('C', 12345);
 define('C', 123);
&#63;>

This code will report a notice error. The consequence is: before you define it, if someone else defines a constant with the same name, you may not really know what value it contains.

2. How to determine whether a PHP constant is defined? It is easy to make mistakes when writing the judgment method

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

3. Low execution efficiency

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

Because PHP needs to perform multiple searches when processing constants, the efficiency is low.

Summary: The problem with PHP constants is that PHP’s method of dealing with constants is too loose. If it can be stricter, many problems will be avoided. In the actual process, do not use constants if you can use variables, because variables are more efficient and more convenient to use.

So if you have to use constants or class variables, you can use the following methods:

<&#63;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;
  }
 }
&#63;>

What happens when the class name and function name are the same

In PHP 4, the constructor of a class needs to be the same as the class name, and the constructor name of a subclass must be the same as the subclass name. The constructor of the parent class will not be automatically executed in the subclass. To execute the constructor of the parent class in a subclass, you must execute a statement similar to the following:

$this->[Constructor name of parent class ()]

In PHP 5.0 and above, construct() is uniformly used as the constructor, but it is still compatible with the constructor definition rules of version 4.0. If both the 4.0 constructor and the construct() function are defined, the construct() function takes precedence.

Use PHP EOL to replace /r/n for line break

Line breaks are often used when writing programs. Use PHP’s built-in constant PHP_EOL to perform line breaks.

A small line break, which has different implementations on different platforms. In the unix world, n is used to replace line breaks, but in order to reflect the difference, windows uses rn. What is more interesting is that r is used in mac. Therefore, the unix series uses n, the windows series uses rn, and the mac uses r.

Therefore, the system will convert into different line breaks depending on the platform system. If you want to wrap the line in the browser, you need to use the PHP_EOL variable to wrap the line

How to use PHP constants?

1. Constants are generally capitalized
define('MYSTR', "My constant");
2. A constant cannot be defined repeatedly and is a fixed value. Relative to variables

In the output of constants in php, under what circumstances does constant(), this function, need to be used?

Constant representation will not change and can only be assigned once. The definition of a constant is using the define function: define('PAI', 3.14);

echo constant('PAI'); The effect is equal to: echo PAI ;

So the constant function is generally not used

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/877513.htmlTechArticleA few things to pay attention to when using PHP constants (use constants in PHP with caution), why you should be cautious about PHP constants Using constants in PHP? The Zend Framework documentation writes: Constants contain numeric words...
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!