search
HomeBackend DevelopmentPHP TutorialPHP 6:PHP 基本数据类型

本章将介绍PHP基本类型。
相信我们已经熟悉了C/C++,C#或者Java里的任意一种语言。本章会以C#为比较语言。
OK,如果你想学PHP,你最先考虑的是什么呢?
我相信肯定是下面的几个问题:
PHP有哪几种数据类型,它们和其他语言有什么区别呢? 一种语言对于数据类型,有强类型和弱类型之分,PHP属于哪一种呢? PHP有什么独特的地方呢? 基于上面想法,我将会一一阐述。
还是先把上一篇文章所引用的代码拿出来吧。

PHP实例代码
 1 function display_user_urls($url_array)
 2 {
 3   // display the table of URLs
 4 
 5   // set global variable, so we can test later if this is on the page
 6   global $bm_table;
 7   $bm_table = true;
 8 ?>
 9   

10   


11   
12   13   $color = "#cccccc";
14   echo "";
15   echo "";
16   if (is_array($url_array) && count($url_array)>0)
17   {
18     foreach ($url_array as $url)
19     {
20       if ($color == "#cccccc")
21         $color = "#ffffff";
22       else
23         $color = "#cccccc";
24       // remember to call htmlspecialchars() when we are displaying user data
25       echo "";
26       echo "";
28       echo ""; 
29     }
30   }
31   else
32     echo "";
33 ?>
34   
BookmarkDelete?
".htmlspecialchars($url)." 27              value=\"$url\">
No bookmarks on record
 
35   

36 37 } 逐一讨论吧。
PHP有哪几种数据类型,它们和其他语言有什么区别呢?       PHP支持8种原始的数据类型。
其中包括4种标量类型:
Integer Float String Boolean 同时包括2种复合类型:
Array Object 但是还有2种特殊的类型:
NULL Resource 写到此,你可能心里开始犯嘀咕:那么它们是在程序里面怎么表示呢?好的,让我们先看看前面6种数据类型吧。还有2种类型后面解释。
Integer:int Float:float String:string Boolean:bool 其实上面的和C# 没有多大区别,这里不多说了。
Array数据类型还是比较特殊的,因为在C#语言里就没有这种数据类型,其他语言,C/C++,Java也是没有的。你可以把他当成C#里的数组看待就可以了。另外,看看PHP官方网站上是怎么说的。
   PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。
看看Array的用法吧。我们可以新建一个Array对象,由于Array是key和value映射的。所以Array支持一定数量以分号分隔的值对。给个例子,代码如下:

php
$arr   =   array ( " Hello "   =>   " Word " ,   12   =>   true );

echo   $arr [ " Hello " ];  //  bar
echo   $arr [ 12 ];     //  1
?>  

请记住一点 :key 可以是整型或者字符串。如果键名是一个整型的标准表达方法,取整,如果是float型,转化为整型。与之对比,值则可以为任何值。
如果你想实现多维数组怎么办?在PHP没有提供类系与C#的多维数组的写法,为什么呢?我的观点是这里的数组早已经不是C# 等语言里的单纯的数组了。它已经扩展了数组,可以哈希表,字典等等。所以提供多维数组确实没有必要。虽说如此,但是可以实现类似的功能,如下代码:

php
$arr   =   array ( " somearray "   =>   array ( 6   =>   5 ,   13   =>   9 ,   " a "   =>   42 ));

echo   $arr [ " somearray " ][ 6 ];     //  5
echo   $arr [ " somearray " ][ 13 ];   //  9
echo   $arr [ " somearray " ][ " a " ];   //  42
?>  

既然讨论到这里,你可能想想知道如何新建或删除一个数组对象。什么都不说了,看看下面代码:

 1  ? php
 2  $arr   =   array ( 5   =>   1 ,   12   =>   2 );
 3  $arr []  =   56 ;     //  相当于 $arr[13] = 56;
 4                  //因为第二个元素的键是12       
 5  $arr [ " x " ]  =   42 ;  //  创建一个新元素,且键为字符串
 6                  //"x",值位42.
 7  unset ( $arr [ 5 ]);  // 删除键位5的元素。
 8  unset ( $arr );     //  删除整个数组
 9                  //unset()是一函数,从字面的意思上                      
                   //看也知道是撤销设置
10  ?>

怎么样,基本上了解了Array了吧。
至于 Object嘛,感觉和C#里的没什么区别。

NULL 对象就有意思了,这个在C# 里是没有的,C#倒是有个null。

特殊的 NULL 值表示一个变量没有值,NULL 类型唯一可能的值就是 NULL。注意了 NULL 类型是 PHP 4 引进的。

在下列情况下一个变量被认为是 NULL:

被赋值为 NULL。

尚未被赋值。

被unset()。

简单吧,原来把C#里的null作为对象了。聪明的家伙们。
既然如此,我们如何判断某个变量为 NULL ,相当的简单,调用is_null(),如何将某个变量设为 NULL ,一种方法是调用unset().

看看 Resource吧,称为资源。它保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。 由于资源类型变量保存为打开文件、数据库连接、图形画布区域等的特殊句柄,因此无法将其它类型的值转换为资源。 由于 PHP4 Zend 引擎引进了资源计数系统,可以自动检测到一个资源不再被引用了(和 Java 一样)。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。由于此原因,很少需要用某些 free-result 函数来手工释放内存。垃圾回收?
除了这些还有其他的吗?当然是肯定的。还有一些伪类型:
         mixed
           mixed 说明一个参数可以接受多种不同的(但并不必须是所有的)类型。

           例如 gettype可以接受所有的 PHP 类型,str_replace可以接受字符串和数组。

        number
            number 说明一个参数可以是 int或float.

        callback
          有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。

2 .一种语言对于数据类型,有强类型和弱类型之分,PHP属于哪一种呢?

             PHP是弱类型的。在PHP里,变量的类型是赋给它们的值决定的。如果赋的值是整型,那么变量就是整型,如果是字符串,就是字符串型。看如下代码:

php
  $name = " your name " ; // name位string类型。
  $total = 12 ;         // total为整型
?>

            那么如何转型呢,我觉得和C# 差不多的。就不赘述了。
       
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

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.

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),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment