search
HomeBackend DevelopmentPHP TutorialA brief introduction to the basics of PHP

A brief introduction to the basics of PHP

Mar 21, 2018 pm 01:24 PM
phpbasic knowledgeSimple

PHP is the best language in the world." This sentence is familiar to everyone! It may lead to another spat. In fact, any programming language has its own advantages and disadvantages, and it can be used in different fields and different environments. It has different functions. I dare not say that PHP is the best language in the world, but I dare to say "I love PHP". I am not a big expert, but I am someone who is familiar with PHP. This article is suitable for people with some basic knowledge of PHP. It is an overview and summary. I hope it will be helpful to everyone!

PHP Introduction

PHP (foreign name: PHP: Hypertext Preprocessor, Chinese Name: "Hypertext Preprocessor") is a general open source scripting language. PHP was originally the abbreviation of Personal Home Page and has been officially renamed "PHP: Hypertext Preprocessor". It is more than 20 years old and its syntax has absorbed the C language. , Java and Perl features, easy to learn, widely used, mainly suitable for web development. PHP's unique syntax mixes C, Java, Perl and PHP's own syntax, which can execute dynamic web pages faster than CGI or Perl. . Compared with other programming languages, dynamic pages made with PHP embed programs into HTML (an application under the standard universal markup language) document for execution, and the execution efficiency is much higher than CGI that completely generates HTML tags. ; PHP can also execute compiled code. Compilation can encrypt and optimize code running, making the code run faster.

PHP Basic Syntax

# #1. Names are case sensitive

Variable names, constant names, array indexes (key names) are all

case sensitive , the names must be consistent

Function names, method names, class names, magic constants, NULL, TRUE, FALSE, forced type conversion, these are all case-insensitive. ’s


2. Variables, constants

Naming:

Mark variables with "$" and cannot numbers, spaces, . to start with, but can have Chinese characters, such as $variable=123;

Variable variables:

$a = 'aa'; $$a = 'bb'; Then $aa = 'bb';

Reference assignment:

$a='123'; $b =

&$a; Quite Since $a and $b both point to a space in memory, if the value of $a is changed, $b will also change. Similar to C language &, the difference is that unset($a), $b still exists. #Variable type: Integer int, floating point float, string string, boolean, array array, object object, resource resource, empty null

Global variables: Global variables themselves are static storage methods, and all global variables are static variables

                          $_SEESION, $_COOKIE, $_POST, $_GET, $_REQUEST, $_FILES, $_EVN, $GLOBALS

Static variables:

static

                 

                                                                                                                                                                                                   Declare it to be global)

            2. Static local variables only take effect within the function body, which is relatively safe. Therefore, it is recommended to use static local variables


Static global variables are also global variables. They are at the same level as $_GET, $_POST, $_FILES and have the same storage location (as are constants)


Static method:

Static method can be used directly without the class being instantiated. For example, Math::MAX($a,$b); calls the static method directly without instantiating the Math class.

Constants: define('constant name', 'constant value',$flag=false); $flag If true, it is not case-sensitive. The default is false, which is size-sensitive. Write;

Predefined constants: PHP_OS, PHP_VERSION,

E_ERROR=1 error, causing the script to terminate; E_WARNING=2 warning, the script does not terminate; E_NOTICE=8 non- Critical error

Magic constants: Magic constants can be uppercase or lowercase. They are not case-sensitive. They all return the physical path. Even if they are included in the output, the output is the source code information, not the currently included file. Information, distinguished from $_SERVER.

(1). __FILE__ Current file path
(2). __DIR__ Current file directory
(3). __LINE__ In The line of the file
(4). __FUNCTION__ In the function in the current file Returns the function name
(5). __CLASS__ In the class in the current file Returns the class name

(6). __METHOD__ In the current file Return the class name in the method in the class of the file::Method name

Summary:

(Global) constants: (Default constants are global) stored in the (static) data segment

Variables: global variables (static data segment), local variables (stored on the stack), static variables (whether global or local are stored in the static data segment)

3. Type Conversion

1. Get the type of variable getType($a);

2. Set the type of variable setType($a,'type '); Types include boolean, integer, float, string, array, object, null

## 3. Forced type conversion, (same type as above)

## $ b = (int) $ a; Convert to plastic surgery


# 4. Type conversion function


# intval(), convert to an integer; floatval(); convert to a floating point type; strval(); get the string of the variable


## 5. Determine the type


#Q

## This is_callable (); // Determine whether it is a valid function name

# 四 四

Arithmetic operators: addition +, subtraction -, multiplication *, division /, modulo %, auto-increment ++, auto-decrement--

Connection operators:

.

, such as $ str = 'one'

. 'two'; then $str = 'onetwo'; Assignment operators: =, +=, -=, *=, /=, %= , .=

Comparison operators: >, >=,

Logical operators: logical AND and, &&; Logical OR or, ||; Negation not,! ; Logical XOR xor (different returns true on both sides, the same returns false)

Bitwise operators: & (bitwise AND), | (bitwise OR), ^ (bitwise exclusive OR); ~ (bitwise negation); (Bitwise right shift)

Other cloud operators:


## ?: ternary operator, @ ignored Error, => Array subscript, -> Call the properties and methods of the object

                                                                                                                                                                                                                                                       but   but    

#

5. Process control

1. Judgment statement

IF statement

## If(condition) {Statement to be executed when the condition is true} else {Statement executed when the condition is false}

##        Three forms:


##                                                                                                                                                                                                                                                            else { False, statement}


## If (condition){True, statement}

## if (condition){ true, statement} elseif(condition){the second condition is true, statement}...else{false, statement};....indicates that elseif can be used multiple times.

##                                                                                                                                  switch(condition) {

#                                                                                                                                                                                                                                                                          

                                ….

Default statement;

## }

                                                                                                                                                              Condition){ If the condition is true, execute the statement inside; if the condition is false, exit the loop}

DO...WHILE statement: do{ First time directly Execute the loop body, start for the second time, execute according to the condition if it is true, exit the loop if it is false} while (condition)
## FOR statement: for(initial value; condition; change Conditional statement) {Statement in the loop body}. Such as for($i=0; $i

## 3 . Statement to exit the loop body

continue,break;exit Difference:

continue skips the current loop, the loop is still continuing

break jumps out of the current loop Loop, loop termination

exit; Terminate the current script, the code after this line of code will not be executed.

Related recommendations:

php basic knowledge note sharing

php basic knowledge summary (necessary for novices)

PHP Basics

The above is the detailed content of A brief introduction to the basics of PHP. For more information, please follow other related articles on the PHP Chinese website!

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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment