search
HomeBackend DevelopmentPHP TutorialChapter 2: How to write PHP code for getting started with PHP_PHP Tutorial

Chapter 2: How to write PHP code for getting started with PHP_PHP Tutorial

Jul 21, 2016 pm 03:21 PM
phpwebonecodeusegetting StartedWriting methodseveral kindsexistBaseEmbedrecommendofpagestyle

一.在web页面嵌入PHP代码的几种风格
推荐使用标准风格或简短风格

复制代码 代码如下:

//标准风格
echo 'Hello World!';
?>

//简短风格
echo 'Hello World!';
?>


二.代码注释的四种方式
复制代码 代码如下:

//单行注释
/*
* 多行注释
*/
#shell风格注释
/**
* PHPdoc风格注释
*/
?>

三.向浏览器输出字符串的几种方法
复制代码 代码如下:

/*
* echo函数的功能:向浏览器输出字符串
* 函数返回值:void
*/
echo 'echo function!';
echo('
');
/*
* echo函数的功能:向浏览器输出字符串
* 函数返回值:int
*/
print 'print function';
echo('
');
echo print 'echo value of print function. ';
echo('
');
/*
* printf函数的功能:向浏览器输出字符串
* 函数返回值:所打印字符串的长度
*/
printf("a weekend have %d days",7);
echo('
');
echo printf("a weekend have %d days",7);
echo('
');
/*
* sprintf函数的功能:把字符串保存到内存中
* 函数返回值:保存的字符串本身
*/
sprintf('sprintf function');
echo('
');
echo sprintf('sprintf function');
echo('
');
?>

输出结果:
echo function test!
print function test.
print function test. 1
a weekend have 7 days
a weekend have 7 days. 23
sprintf function test
常用类型指示符

类型

描述

%b

整数,显示为二进制

%c

整数,显示为ASCII字符

%d

整数,显示为有符号十进制数

%f

浮点数,显示为浮点数

%o

整数,显示为八进制数

%s

字符串,显示为字符串

%u

整数,显示为无符号十进制数

%x

整数,显示为小写的十六进制数

%X

整数,显示为大写的十六进制数

四.标识符与变量
1.标识符的基本规则:
1) 标识符可以是任意长度,而且可以由任何字母、数字、下划线组成。
2) 标识符不能以数字开始。
3) 在PHP中,标识符是区分大小写的。
4) 一个变量名称可以与一个函数名称相同。
2.变量赋值:
复制代码 代码如下:

$sum = 0;
$total = 1.22;
$sum = $total;
echo $sum; //1.22
?>

3.变量的数据类型:
基本数据类型

类型

名称

Integer

整数

Float

单精度浮点数

Double

又精度浮点数

String

字符串

Boolean

布尔

Array

数组

Object

对象

4.类型强度
PHP是动态语言,是一种非常弱的类型语言,在程序运行时,可以动态的改变变量的类型。
5.类型转换:
隐式类型转换:
复制代码 代码如下:

$sum = 0;
$total = 1.22;
$sum = $total;
echo gettype ( $sum );//double
?>

显式类型转换:
复制代码 代码如下:

$sum = 100;
$total = ( string ) $sum;
echo gettype ( $sum );//string
?>

使用settype()函数进行类型转换,返回值1表示成功,空表示失败。
复制代码 代码如下:

$sum = 58;
echo settype ( $sum, "float" );
echo $sum; //58
echo gettype ( $sum ); //double
?>

6.检测变量的函数:

函数

功能

返回值

Gettype()

获取变量的类型

基本数据类型中的其中一种

Settype()

 设置变量的类型

Bool(1:true 0:false(or ''))

Isset()

用来判断一个变量是否存在

Bool

Unset()

释放给定的变量

Void

Empty()

检测一个变量的值是否为空

Bool

is_int() is_integer()

检测变量是否是整数

Bool

Is_string()

检测变量是否是字符串

bool

Is_numeric

检测变量是否为数字或数字字符串

bool

Is_null

检测变量是否为 NULL

bool

Intval()

获取变量的整数值

int

Isset()的基本使用
复制代码 代码如下:

$a = 10;
echo isset ( $a );//1
?>
echo isset ( $b );//''
?>

Usset()的基本使用
复制代码 代码如下:

$a = 10;
unset($a);
echo isset ( $a );//''
?>

Empty()的基本使用
复制代码 代码如下:

$a= 5;
$b =1;
$c = 0;
$d = "";
$e = array();
$f = null;
$g = "0";
$h = false;
echo empty($a);//''(false)
echo '
';
echo empty($b);//''(false)
echo '
';
echo empty($c);//1(true)
echo '
';
echo empty($d);//1(true)
echo '
';
echo empty($e);//1(true)
echo '
';
echo empty($f);//1(true)
echo '
';
echo empty($g);//1(true)
echo '
';
echo empty($h);//1(true)
echo '
';
echo empty($f);//1(true)
?>

is_int()的基本使用。类似的函数有:is_float()、is_double()、is_string()、is_bool()、is_array()、is_null()、is_long()、is_object()、is_resource()、is_numeric()、is_real()等。
复制代码 代码如下:

$a = 11;
$b = 1.23;
$c = 3.1415926;
$d = "hello";
$e = false;
$f = array();
$g = null;
echo is_int($a);//1
echo '
';
echo is_float($b);//1
echo '
';
echo is_double($c);//1
echo '
';
echo is_string($d);//1
echo '
';
echo is_bool($e);//1
echo '
';
echo is_array($f);//1
echo '
';
echo is_null($g);//1
echo '
';
echo is_numeric($a);//1
?>

Intval()函数的基本使用。类似的函数为:floatval()、strval()
复制代码 代码如下:

$a = 22.23;
echo gettype($a);//double
echo '
';
$b = intval($a);//类型转换后不改变$a原来的类型
echo gettype($a);//double
echo '
';
?>
$a = 22.23;
echo gettype($a);//double
echo '
';
settype($a,"integer");//类型转换后会改变$aa原来的类型
echo gettype($a);//integer
echo '
';
?>

7.变量的作用域

超级全局变量

变量名

作用

$GLOBALS

所有全局变量数组

$_SERVER

服务器环境变量数组

$_GET

通过GET方式传递给该脚本的变量数组

$_POST

通过POST方式传递给该脚本的变量数组

$_COOKIE

COOKIE变量数组

$_FILES

与文件上传相关的变量数组

$_ENV

环境变量数组

$_REQUEST

所用用户输入的变量数组

$_SESSION

会话变量数组


8. Constants
Once defined, they cannot be changed again.
Copy code The code is as follows:

define("TOTAL",100);
echo TOTAL;//100
echo '
';
define("TOTAL",200);
echo TOTAL;//100
?>

Methods to view PHP predefined constants
Copy the code The code is as follows:

phpinfo();
?>

Method to reference PHP predefined constants
Copy code Code As follows:

echo $_SERVER["SERVER_NAME"];//localhost
echo '
';
echo $_SERVER[ "SERVER_PORT"];//8090
echo '
';
echo $_SERVER["DOCUMENT_ROOT"];//D:/AppServ/www
echo '
';
?>

5. Three common ways to access form variables

Copy code The code is as follows:

echo $username;//Short style, easily confused with variable names, not recommended.
echo '
';
echo $_POST['username'];//Medium style, supported after version 4.1.0, recommended
echo '
' ;
echo $HTTP_POST_VARS['username'];//Long style, outdated, may be eliminated in the future
?>

Posttest.html
Copy code The code is as follows:





How to get form data



username:





6. For string concatenation.
Copy code The code is as follows:

echo "the student name is:".$_POST['username'];
echo "
";
echo "welcome to "."school";
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324815.htmlTechArticle1. Several styles of embedding PHP code in web pages. It is recommended to use standard style or short style to copy the code. The code is as follows: ?php //Standard style echo 'Hello World!'; ? ? //Short style echo '...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.