search
HomeBackend DevelopmentPHP TutorialPHP新手上路(四)_PHP

PHP入门

4.1 数据类型

  PHP支持整数、浮点数、字符串、数组和对象。变量类型通常不由程序员决定而由PHP运行过程决定(真是好的解脱!)。当然,如果你喜欢的话,你也可以使用cast或者函数settype()将某种类型的变量转换成指定的类型。

数值

  数值类型可以是整数或是浮点数。你可以用以下的语句来为一个数值赋值:
$a = 1234; # 十进制数
$a = -123; # 负数
$a = 0123; # 八进制数 (等于十进制数的83)
$a = 0x12; # 十六进制数(等于十进制数的18)
$a = 1.234; # 浮点数"双精度数"
$a = 1.2e3; # 双精度数的指数形式

字符串

  字符串可以由单引号或双引号引出的字段定义。注意不同的是被单引号引出的字符串是以字面定义的,而双引号引出的字符串可以被扩展。而且,在双引号字符串中可以使用反斜杠()在字符串中加入转义序列和转换字符。举例如下:

$first = 'Hello';
$second = "World";
$full1 = "$first $second"; # 产生 Hello World
$full2 = '$first $second';# 产生 $first $second
$full3="01DC studio,." 2000 copyright." " ;

  请注意最后一行,如果需要在字符串中使用双引号,可以使用反斜杠字符,象该行语句所示。这里的的反斜杠用来使双引号的功能改变。

  可以将字符和数字利用运算符号连接起来。字符被转化成数字,利用其最初位置。在PHP手册中有详细的例子。

数组与哈希表

  数组与哈希表以同样的方法被支持。怎样运用取决于你怎样定义它们。你可以用list()或者array()来定义它们,也可以直接为数组赋值。数组的索引从0开始。虽然我在这里没有说明,但是你一样可以轻易的使用多维数组。

// 一个包含两个元素的数组
$a[0] = "first";
$a[1] = "second";
$a[] = "third"; // 添加数组元素的简单方法
// 现在$a[2]被赋值为"third"
echo count($a); // 打印出3,因为该数组有3个元素
// 用一个语句定义一个数组并赋值
$myphonebook = array (
"sbabu" => "5348",
"keith" => "4829",
"carole" => "4533"
);
// 噢,忘了教长吧,让我们添加一个元素
$myphonebook["dean"] = "5397";
// 你定义的carale元素错了,让我们更正它
$myphonebook["carole"] => "4522"
// 我还没有告诉你怎样使用数组的相似支持方式吗?让我们看一看
echo "$myphonebook[0]"; // sbabu
echo "$myphonebook[1]"; // 5348

其他一些对数组或哈希表有用的函数包括sort(),next(),prev()和each()。

对象

  使用new语句产生一个对象:
class foo
{
function do_foo ()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();

改变变量类型

  在PHP手册中提到:"PHP不支持(也不需要)直接在声明变量时定义变量类型;变量类型将根据其被应用的情况决定。如果你为变量var赋值为一个字符串,那么它变成了一个字符串。如果你又为它赋了整数值,那么它就变成了整数。"

$foo = "0"; // $foo是字符串(ASCII 48)
$foo++; // $foo是字符串"1" (ASCII 49)
$foo += 1; // $foo现在是整数(2)
$foo = $foo + 1.3; // $foo是一个双精度数(3.3)
$foo = 5 + "10 Little Piggies"; // $foo是一个整数(15)
$foo = 5 + "10 Small Pigs"; // $foo是一个整数(15)

如果想要强行转换变量类型,可以使用与C语言相同的函数settype()。

4.2 变量与常量

  可能你已经注意到,变量都有一个美元符号($)的前缀。所有变量都是局部变量,为了使得定义的函数中可以使用外部变量,使用global语句。而你要将该变量的作用范围限制在该函数之内,使用static语句。
$g_var = 1 ; // 全局范围
function test()
{
global $g_var; // 这样就可以声明全局变量了
}

  更先进一些的是变量的变量表示。请参考PHP手册。这在有时会显得很有用。

  PHP内置了许多已定义的变量。你也可以用define函数定义你自己的常量,比如define("CONSTANT","value")。

4.3 运算符

  PHP具有C,C++和Java中的通常见到的运算符。这些运算符的优先权也是一致的。赋值同样使用"="。

算术和字符

  以下只有一种运算符是有关字符的:
$a + $b :加
$a - $b :减
$a * $b :乘
$a / $b :除
$a % $b :取模(余数)
$a . $b :字符串连接

逻辑和比较

逻辑运算符有:
$a || $b :或
$a or $b :或
$a && $b :与
$a and $b :与
$a xor $b :异或 (当$a或$b为true时为true,两者一样时为false)
! $a :非
比较运算符有:
$a == $b :相等
$a != $b :不等
$a $a $a > $b :大于
$a >= $b :大于等于
与C一样PHP也有三重运算符(?:)。位操作符在PHP同样存在。

优先权

就和C以及Java一样!

4.4 控制流程结构

  PHP有着与C一样的流程控制。我将在下面大概介绍。

if, else, elseif, if(): endif

if (表达式一)
{
. . .
}
elseif (表达式二)
{
. . .
}
else
{
. . .
}
// 或者像Python一样
if (表达式一) :
. . .
. . .
elseif (表达式二) :
. . .
else :
. . .
endif ;

Loops. while, do..while, for

while (表达式)
{
. . .
}
do
{
. . .
}
while (表达式);
for (表达式一; 表达式二; 表达式三)
{
. . .
}
//或者像Python一样
while (expr) :
. . .
endwhile ;

switch

switch是对多重if-elseif-else结构的最好的替换:
switch ($i)
{
case 0:
print "i equals 0";
case 1:
print "i equals 1";
case 2:
print "i equals 2";
}

break, continue

break中断当前的循环控制结构。
continue被用来跳出剩下的当前循环并继续执行下一次循环。

require, include

  就像C中的#include预处理一样。你在require中指定的那个文件将替代其在主文件中的位置。在有条件的引用文件时,可以使用include()。这样就使得你可以将复杂的PHP文件分割成多个文件并且在不同需要时分别引用它们。

4.5 函数

  你可以像以下的例子一样定义自己的函数。函数的返回值可以是任何数据类型:
function foo (变量名一, 变量名二, . . . , 变量名n)
{
echo "Example function.n";
return $retval;
}

  所有PHP代码都可以出现在函数定义中,甚至包括对其他函数和类的定义。函数必须在引用之前定义。

4.6 类

  利用类模型建立类。可以参考PHP手册中对类的详细解释。
class Employee
{
var $empno; // 员工人数
var $empnm; // 员工姓名

function add_employee($in_num, $in_name)
{
$this->empno = $in_num;
$this->empnm = $in_name;
}

function show()
{
echo "$this->empno, $this->empnm";
return;
}

function changenm($in_name)
{
$this->empnm = $in_name;
}
}

$sbabu = new Employee;
$sbabu->add_employee(10,"sbabu");
$sbabu->changenm("babu");
$sbabu->show();


type="text/javascript"> type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> (责任编辑:超越PHP)
[推荐给朋友] [显示打印版本] 更新日期:2002-08-24 浏览次数: language='Javascript' src='/view.php?aid=47'>
language="JavaScript" src="/note_show.php" type="text/javascript">
view source | feedback | send page | sitemap | aboutus   
Copyright © 2002-2006 PHPE TEAM. All rights reserved
Last updated:04/21/06 04:55:56 中国标准时间
Server sponsored by cncms.org

PHP新手上路(四)_PHP
 
src="http://www.google-analytics.com/urchin.js" type="text/javascript"> type="text/javascript"> _uacct = "UA-156767-2"; urchinTracker(); language="JavaScript" type="text/javascript" src="/js/pphlogger language="JavaScript" type="text/javascript" src="/site_online.php?hide=1&file=article_show.php">
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: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.