Table of Contents
变量
变量定义
变量赋值
数据类型
字符串
整数
浮点数
布尔型
数组
对象
NULL
资源
作用域
global关键词
static关键词
Home Backend Development PHP Tutorial 前端学PHP之变量、数据类型及作用域

前端学PHP之变量、数据类型及作用域

Jun 23, 2016 pm 01:20 PM

目录[1]变量变量定义变量赋值[2]数据类型字符串整数浮点数布尔型数组对象NULL资源[3]作用域globalstatic

变量

变量定义

变量是存储信息的容器,以$符号开头,其后是变量名称。变量名称必须以字母或下划线开头,对大小写敏感

<?php$x=5;//5echo $x;//什么都不输出echo $X;?>
Copy after login

变量赋值

PHP没有创建变量的命令,变量会在首次为其赋值时被创建

<?php$txt="Hello world!";$x=5;$y=10.5;?>
Copy after login

数据类型

PHP是一门类型松散的语言,不必告知PHP变量的数据类型,PHP会根据它的值,自动把变量转换成正确的数据类型。PHP数据类型包括8种:其中包括四种标量类型、两种复合类型和两种特殊类型。具体是:字符串、整数、浮点数、布尔、数组、对象、NULL、资源

[注意]var_dump() 会返回变量的数据类型和值

字符串

字符串可以是引号内的任何文本,引号可以是单引号或双引号

<?php $x = "Hello world!";//Hello world!echo $x;echo "<br>"; $x = 'Hello world!';//Hello world!echo $x;?>
Copy after login

<情况1>当字符串中包含引号,有三种解决方案:

[1]单引号中嵌入双引号

[2]双引号中嵌入单引号

[3]使用转义符"\"

<?php $str_string1 = '"test"';$str_string2 = "'test'";$str_string3 = '\'test\'';echo $str_string1;echo "<br />";echo $str_string2;echo "<br />";echo $str_string3;?>
Copy after login

<情况2>当字符串的引号遇到变量,分为两种情况:

[1]当双引号中包含变量时,变量会与双引号中的内容连接在一起

[2]当单引号中包含变量时,变量会被当作字符串输出

<?php $test = 1;$str_string1 = ' $test ';$str_string2 = " $test ";$str_string3 = ' "$test" ';$str_string4 = " '$test' ";echo $str_string1;//$testecho "<br />";echo $str_string2;//1echo "<br />";echo $str_string3;//"$test"echo "<br />";echo $str_string4;//'1'?>
Copy after login

<情况3>当字符串很长时,使用Heredoc结构形式的方法,首先定界符表示字符串(<<<),接着在(<<<)之后提供一个标识符(任意名称),换行后是字符串,最后以这个标识符结束字符串。注意标识符左右不要有多余的空格

<?php $str = <<< G123G;echo $str;//123?>
Copy after login

整数

PHP整数必须至少有一个数字,不能包含逗号或空格,不能有小数点,正负均可,可以用三种格式规定整数:十进制、十六进制(前缀是0x)或八进制(前缀是0)

<?php $x = 5985;//int(5985)var_dump($x);echo "<br>"; $x = -345; // int(-345)var_dump($x);echo "<br>"; $x = 0x11; // int(17)var_dump($x);echo "<br>";$x = 011; // int(9)var_dump($x);?>
Copy after login

浮点数

PHP浮点数是有小数点或指数形式的数字

<?php $x = 10.365;//float(10.365)var_dump($x);echo "<br>"; $x = 2.4e3;//float(2400)var_dump($x);echo "<br>"; $x = 8E-1;//float(0.8)var_dump($x);?>
Copy after login

布尔型

PHP布尔型只有两个值:true或false(不区分大小写),常用于条件测试。当用echo指令输出布尔类型时,如果是true,则输出"1",false则什么都不输出

<?php     $man = "男";    $flag = $man == "男";//输出1    echo $flag ;    echo "<br />" ;    $flag = $man == "女";//什么都不输出    echo $flag;    var_dump($flag);//bool(false)?>
Copy after login

数组

PHP数组可以在一个变量中存储多个值

<?php $cars=array("Volvo","BMW","SAAB");//array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(4) "SAAB" }var_dump($cars);?>
Copy after login

对象

PHP对象是存储数据和有关如何处理数据的信息的数据类型。在PHP中,必须明确地声明对象,但首先必须声明对象的类。对此,使用class关键词,类是包含属性和方法的结构。然后在对象类中定义数据类型,然后在该类的实例中使用此数据类型

<?phpclass Car{    var $color;    function Car($color="green") {      $this->color = $color;    }    function what_color() {      return $this->color;    }}function print_vars($obj) {   foreach (get_object_vars($obj) as $prop => $val) {     echo "\t$prop = $val\n";   }}$herbie = new Car("white");echo "\herbie: Properties\n";print_vars($herbie);?>
Copy after login

NULL

PHP中的NULL是空类型,对大小写不敏感,NULL类型只有一个取值,表示一个变量没有值,当被赋值为NULL,或者尚未被赋值,或者被unset(),这三种情况下变量被认为为NULL

<?php  error_reporting(0); //禁止显示PHP警告提示 $var; var_dump($var);//NULL $var1 = null; var_dump($var1);//NULL $var2 = NULL; var_dump( $var2);//NULL $var3 = "节日快乐!"; unset($var3); var_dump($var3);//NULL?>
Copy after login

资源

PHP资源是由专门的函数来建立和使用的,例如打开文件、数据连接、图形画布。可以对资源进行操作(创建、使用和释放)。任何资源,在不需要的时候应该被及时释放。如果我们忘记了释放资源,系统自动启用垃圾回收机制,在页面执行完毕后回收资源,以避免内存被消耗殆尽

<?php$file=fopen("data/webroot/resource/f.txt","r");   //打开文件$con=mysql_connect("127.0.0.1","root","root");  //连接数据库if ($file_handle){    //接着采用while循环(后面语言结构语句中的循环结构会详细介绍)一行行地读取文件,然后输出每行的文字    while (!feof($file_handle)) { //判断是否到最后一行        $line = fgets($file_handle); //读取一行文本        echo $line; //输出一行文本        echo "<br />"; //换行    }}fclose($file_handle);//关闭文件?>
Copy after login

[注意]memory_get_usage() 会获取当前PHP消耗的内存,单位为byte

<?php echo $m1 = memory_get_usage(); echo "<br />";$var_string = '123';//320echo $m2 = memory_get_usage()-$m1; echo "<br />";$n = 123;//272echo $m3 = memory_get_usage()-$m1-$m2; echo "<br />";$f = 123.00;//272echo $m4 = memory_get_usage()-$m1-$m2-$m3; echo "<br />";$var_array = array('123');//576echo $m5 = memory_get_usage()-$m1-$m2-$m3-$m4; ?>
Copy after login
<?php   $string = "就是就是"; var_dump($string);//string(12) "就是就是" echo "<br />"; $string = 9494; var_dump($string);//int(9494)  echo "<br />";?>
Copy after login

作用域

PHP有三种不同的变量作用域:local(局部)、global(全局)、static(静态)

函数之外声明的变量有global作用域,只能在函数以外进行访问;函数内部声明的变量有local作用域,只能在函数内部进行访问

<?phperror_reporting(0); //禁止显示PHP警告提示$x=5; // 全局作用域function myTest() {  $y=10; // 局部作用域  echo "<p>测试函数内部的变量:</p>";  echo "变量 x 是:$x<br>";  echo "变量 y 是:$y";} //无输出//10myTest();echo "<p>测试函数之外的变量:</p>";echo "变量 x 是:$x<br>";//5echo "变量 y 是:$y";//无输出?>
Copy after login

global关键词

用于访问函数内的全局变量

<?php$x=5;$y=10;function myTest() {  global $x,$y;  $y=$x+$y;}myTest();echo $y; // 输出 15?>
Copy after login

PHP同时在名为GLOBALS[index]的数组中存储了所有的全局变量,下标存有变量名。这个数组在函数内也可以访问,并能够用于直接更新全局变量

<?php$x=5;$y=10;function myTest() {  $GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];} myTest();echo $y; // 输出 15?>
Copy after login

static关键词

通常,当函数完成或执行后,会删除所有变量,不过,有时需要不删除某个局部变量。要完成这一点,需要在首次声明变量时使用static关键词。每当函数被调用时,这个变量所存储的信息都是函数最后一次被调用时所包含的信息,但要注意的是,这个变量仍然是函数的局部变量

<?phpfunction myTest() {   static $x=0;   echo $x;   $x++;}myTest();//0echo "<br>";myTest();//1echo "<br>";myTest();//2echo "<br>";myTest();//3echo "<br>";myTest();//4?>  
Copy after login
Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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 API Introduction to the Instagram API Mar 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 Laravel Working with Flash Session Data in Laravel Mar 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-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 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

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 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' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 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 CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 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 Survey Announcement of 2025 PHP Situation Survey Mar 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