搜索
首页后端开发php教程[Zend PHP5 Cerification] Lectures -- 1. PHP Basics, PHP Functions, Arrays

PHPBasics

PHPBasics refers to a number of things that

arelikely already second nature to you:

?Syntax

?Operators

?Variables

?Constants

?Control Structures

LanguageConstructs and Functions

 

 

 

 

Magicconstants
__LINE__   The current linenumber of the file.
__FILE__   The full path andfilename of the file. If used inside an include, the name of theincluded file is returned. Since PHP 4.0.2, __FILE__always contains an absolute path whereas in older versions itcontained relative path under some circumstances.
__FUNCTION__   The function name.(Added in PHP 4.3.0) As of PHP 5 this constant returns the functionname as it was declared (case-sensitive). In PHP 4 its value isalways lowercased.
__CLASS__   The class name. (Addedin PHP 4.3.0) As of PHP 5 this constant returns the class name as itwas declared (case-sensitive). In PHP 4 its value is alwayslowercased.
__METHOD__   The class method name.(Added in PHP 5.0.0) The method name is returned as it was declared(case-sensitive).

 

PHPlanguage construct

The "exact"  definition for "LanguageConstruct".

It's kind of like the "core languagedefinition" of things such as: if (...) while (...) and so on In PHP, a handful of common things that manybeginners *THINK* are functions are actually Language Constructs:require include echo isset I belive most of them are documented assuch in the manual now. Language Construct roughly corresponds to the"grammar" of the language, if you will.

Thismeans that they are integral part of the language, just like 'if', orany operator +, *, etc, though they look pretty much like functions.It means that though syntactically they look a functions and in themanual they are listed under functions, this is only to make themeasy to use, understand and locate in the documentation. That is whycertain rules for functions can be relaxed, such as requiringparenthesis around its arguments, which are not actually needed butare there so that they have the same look as regular functions.

 

PHP Tags

Long tags:

Script syle tags:

Short tags: short_open_tag directive inphp.ini

…?> ( echo $vars ?>;= $vars ?>)

ASP style tags: asp_tags directive inphp.ini

(;)

 

Except the long tags, other tags are notpreferred.

 

Exam questions:

.When you should not use short tags? When usephp with XML.

What kind of errors occurred due to the “shorttags” problem?

A. output javascript source code;

B. Parse error: syntax error,unexpected $end in

 

Use the long or regular PHP tags to ensureyour application will be portable across multiple servers regardlessof configuration options.

 

 

Comments

// single line comment

# single line comment

/*

Multi-line comment

*/

.PHPdoc comment style

 

Single line comments are ended by either thenewline character or a closing PHP tag, so a single like comment like

//This tag ?> can end PHP code

Can have unintended output

 

Variables

PHPis loosely typed.

Scalar:Boolean, string, integer, float

Compound:array, object

Special:resource, null

 

ScalarTypes

 

Strings

Natively within PHP each character is represented by asingle byte, as such PHP has no native support for multi-bytecharacter sets (like Unicode)

This changeswith PHP6.

There is no PHP imposed limit on the length of the strings youcan use.

‘’ The single quote or string literal, characters within singlequotes will be recorded as is, without variable or escape sequencesinterpreted and replaced.

“” The double quotes, variables and escape sequnces will beinterpreted and replaced

Theheredoc syntax functions in a similar manner to double quotes, but isdesigned to span multiple lines, and allow for the use of quoteswithout escaping.

$greeting=

Shesaid "That is $name's" dog!

Whilerunning towards the thief

GREETING;

 

Also,the identifier used must follow the same naming rules as any otherlabel in PHP: it must contain only alphanumeric characters andunderscores, and must start with a non-digit character or underscore.

 

Itis very important to note that the line with the closing identifiercontains no other characters, except possibly a semicolon (;). Thatmeans especially that the identifier may not be indented, and theremay not be any spaces or tabs after or before the semicolon. It'salso important to realize that the first character before the closingidentifier must be a newline as defined by your operating system.This is \r on Macintosh for example. Closing delimiter (possiblyfollowed by a semicolon) must be followed by a newline too.

 

Itis not allowed to use heredoc syntax in initializing class members.Use other string syntaxes instead.

 

Integer

0

0x

Maximum size of an integer is platformdependent, a maximum of ~2Billion is common.

 

Float (double)

Floats, or doubles, can be used to representreally

large or really small values. Floats can beentered

via several syntaxes

$a = 1.234; //Standard decimal notation

$b = 1.2e3; //Scientific notation (1200)

$c = 7E-10;

//Scientific notation (0.0000000007)

? The size of a float is platform-dependent,although a

maximum of ~1.8e308 with a precision

 

 

I encountered a questions on the numbernotation conversion. But is relative easy. By default, php is outdecimal numbers.

 

 

Boolean

True, false, 0, 1… case-insensitive

 

 

CompoundTypes

Arrays

Arrays cancontain any combination of other variable types, even arrays orobjects.

More details onlater lectures.

 

Objects

Objects allowdata and methods to be combined into one cohesive structure.

More details onlater lectures.

 

SpecialTypes

Resource

Aresource is a special variable that represents some sort of operatingsystem resource, generally an open file or database connection.

Whilevariables of the type resource can be printed out, their onlysensible use is with the functions designed to work with them.

Null

Anull variable is special in that it has no value and no type.

Nullis not the same as the integer zero or an zero length string (whichwould have types)

 

 

 

Constants

Constants allowyou to create a special identifier that can not be changed oncecreated, this is done using the define() function. Constants can notbe changed once set.

define('username','bob');

 

VariableVariables

Variable Variables are bothuseful and confusing:

$a= 'name';

$$a= "Paul";

echo$name; //Paul

 

There are several situationsin which Variable

Variablescan be useful, but use them with care as

theycan easily confuse other programmers.

 

 

Operators

?PHP supports a multitude of Operators:

?Assignment

?Logical

?Arithmetic

?String

?Comparison

?Bitwise

?Other

 

.AssignmentBy Value vs By Reference

PassObjects argument in PHP5.

 

UsingBitwise Operations: &(and), |(or), ^(XOR), ~(NOT)

>>(ShiftRight),

Whatis the output of:

? 1& 2

? 2& 7

? 15& 24

? 1| 2

? 16| 15

? 8^ 6

? 15^ 7

 

Whatis the output of (within the context of

our8 bit binary world):

?~254

? 4>> 2

? 1

? 5>> 2

?7

 

 

OtherOperators

@:Suppresses errors from the following expression

``backticks:Execute the contents as a shell command

(shortcutfor shell_exec()).

Instanceof:Returns true if the indicated variable is an instance of thedesignated class, one of it’s subclasses or a designated interface.

 

Instanceofis somewhat important, cause I encounter some exam questionsregarding this.

 

ini_set("ERROR_LEVEL",E_STRICT);

$a= @myFunction();

functionmyFunction($a)

{

array_merge(array(),"");

}

 

 

$ls= `ls`;

 

 

$a= new stdClass;

if($a instanceof stdClass) { ... }

if($a !instanceof stdClass) { ... }

//ParseError

 

ControlStructures

If

?Alternate * code morereadable.

?Short ($express)?$var1:$var2

Switch

While

do

For

?Continue

?break

Foreach

Functions

?Paramaters

? Optional

? Byref

? Byval

? Objects

? Variable functions

Objects

Later!

 

if,while, do, for, foreach can have alternate syntax, replace the { and} with : and end(if, while, do etc). Check some WordPress theme filefor real world example.

 

 

$a= 0;

while($a++

{

echo$a;

}

echo$a;

 

 

return

Returnends execution and returns control to the calling scope, functionsboth inside an included file (returning control to the calling file)and from inside a function/method (returning control to the callingcode).

 

Exit

Haltexecution of the script, can optionally return a message, or an exitstatus (0-255).

 

Arare exam questions:

 

End ascript in PHP5:
    __halt_compiler() ;
   die();
    exit();

 

Conclusion

?PHP Tags, multiple types withdifferent use rules (which ones are on/off by default, which ones aguaranteed?)

?PHP is loosely typed, but there istyping going onunderneath the hood

?Some assumptions are made (octalformat)

?Binary is a pain in the neck, but ithas its

uses

?Control structures have formats otherthan

theones commonly uses

 

PHPFunctions

?Readability

?Maintainability

?Code separation

?Modularity

 

Functions? Scope

Ithink this should expanded to cover the features related to variablescope: Super Global, global variable, local variables, classmembers(public, private, protect, final etc), constant, static etc.

ButPHP free memory on the end of every page load, so even staticvariable can across separate http request; that’s why we needcookies and sessions.

 

 

global $id;

globals[‘id’];

 

Theexam has several questions will need you to clearly understand theFunction Scope. And pass value Byref and Byval.

 

variable-lengthargument lists

Youcan use variable-length argument lists even if you do specifyarguments in the

functionheader.

func_get_args,func_num_args, func_get_arg

 

 

Functions& Objects, Friends at last

? InPHP4 Objects were thrown around ByVal,this meant that you made copies without

eventhinking about it.

? InPHP5 Objects are always passed ByRefunless you explicitly clone it, keep that in

Mind.

 

Conclusion

They’reterribly useful

?You have to remember how scope works

?Practice tracing

?Objects fly around by reference now

?Return statements can exist anywherewithin thefunction, you can even have several

?Avoid situations where the samefunction mayreturn nothing, or something (Zend

Studio’sCode Analyzer tests for this)

 

Whathappens if a function is defined then the PHP scope ends, thenresumes again later with the remainder of the function.

 

Is“_” a valid function name?

 

PHPArrays

EnumeratedArrays, Associative Arrays (hashes), Multi Dimensional Arrays

 

$a =array(5=>"b", 7, 9, "23" => 'c', 'j');
$b= array(1, 2, 3, 'f', 'fred' => $a);
 How do I access thevalue:
? 7                                       //  $a[6];
? ‘c’                                      // $a["23"];
? ‘b’ through the array $b        // $b['fred'][5]
? ‘f’                                       // $b[3]

ArrayIteration:

Wheniterating through an array via foreach() keep in mind it operates ona copy of the array.

 

Usingthe internal array pointer doesn’t have this problem.

 

ArrayIteration

?end() ? Move pointer tolast element

?key() - Retreives keyfrom current position

?next() ? Advances arraypointer one spot then

returnscurrent value

?prev() ? Rewinds thearray pointer one spot, then

returnsthe current value

?reset() ? Resets thearray pointer to the beginning of

thearray

?each() ? Returns the

 

Internalarray pointers can be reset, but don’t reset on their own.

 

Foreach()

InPHP 5 items can be iterated over by reference rather than simply byvalue.

foreach($arrayAS &$value) { … }

 

Thisis likely will be examed!

 

SomeArray functions:

 

.sort()
Thisfunction sorts an array. Elements will be arranged from lowest tohighest when this function has completed.
This function assignsnew keys for the elements in array. It will remove any existing keysyou may have assigned, rather than just reordering thekeys.
.Ksort()
Sorts an array by key, maintaining key todata correlations. This is useful mainly for associativearrays.
.asort()
Sort an array and maintain indexassociation

array_push() array_unshift()
array_pop()    array_shift()

 
Inassociative arrays strings are used to key the data, keys containingonly digits are cast to integers.

array_keys() &array_values()

bool array_walk ( array &$array, callback$funcname [, mixed $userdata] )
Applies the user-defined functionfuncname to each element of the array array. Typically, funcnametakes on two parameters. The array parameter's value being the first,and the key/index second. If the optional userdata parameter issupplied, it will be passed as the third parameter to the callbackfuncname.


array_change_key_case()
Returns an array withall keys from input lowercased or uppercased. Numbered indices areleft as is.


array_merge()
You can merge arrays usingarray_merge(), when different associative arrays have duplicate keys,the values in the rightmost array takeprecedence.

array_splice()
Cut out a chunk of anarray

array_merge_recursive()
merges the elements of one ormore arrays together so that the values of one are appended to theend of the previous one. It returns the resulting array.

Ifthe input arrays have the same string keys, then the values for thesekeys are merged together into an array, and this is done recursively,so that if one of the values is an array itself, the function willmerge it with a corresponding entry in another array too. If,however, the arrays have the same numeric key, the later value willnot overwrite the original value, but will be appended.

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP:服务器端脚本语言的简介PHP:服务器端脚本语言的简介Apr 16, 2025 am 12:18 AM

PHP是一种服务器端脚本语言,用于动态网页开发和服务器端应用程序。1.PHP是一种解释型语言,无需编译,适合快速开发。2.PHP代码嵌入HTML中,易于网页开发。3.PHP处理服务器端逻辑,生成HTML输出,支持用户交互和数据处理。4.PHP可与数据库交互,处理表单提交,执行服务器端任务。

PHP和网络:探索其长期影响PHP和网络:探索其长期影响Apr 16, 2025 am 12:17 AM

PHP在过去几十年中塑造了网络,并将继续在Web开发中扮演重要角色。1)PHP起源于1994年,因其易用性和与MySQL的无缝集成成为开发者首选。2)其核心功能包括生成动态内容和与数据库的集成,使得网站能够实时更新和个性化展示。3)PHP的广泛应用和生态系统推动了其长期影响,但也面临版本更新和安全性挑战。4)近年来的性能改进,如PHP7的发布,使其能与现代语言竞争。5)未来,PHP需应对容器化、微服务等新挑战,但其灵活性和活跃社区使其具备适应能力。

为什么要使用PHP?解释的优点和好处为什么要使用PHP?解释的优点和好处Apr 16, 2025 am 12:16 AM

PHP的核心优势包括易于学习、强大的web开发支持、丰富的库和框架、高性能和可扩展性、跨平台兼容性以及成本效益高。1)易于学习和使用,适合初学者;2)与web服务器集成好,支持多种数据库;3)拥有如Laravel等强大框架;4)通过优化可实现高性能;5)支持多种操作系统;6)开源,降低开发成本。

揭穿神话:PHP真的是一种死语吗?揭穿神话:PHP真的是一种死语吗?Apr 16, 2025 am 12:15 AM

PHP没有死。1)PHP社区积极解决性能和安全问题,PHP7.x提升了性能。2)PHP适合现代Web开发,广泛用于大型网站。3)PHP易学且服务器表现出色,但类型系统不如静态语言严格。4)PHP在内容管理和电商领域仍重要,生态系统不断进化。5)通过OPcache和APC等优化性能,使用OOP和设计模式提升代码质量。

PHP与Python辩论:哪个更好?PHP与Python辩论:哪个更好?Apr 16, 2025 am 12:03 AM

PHP和Python各有优劣,选择取决于项目需求。1)PHP适合Web开发,易学,社区资源丰富,但语法不够现代,性能和安全性需注意。2)Python适用于数据科学和机器学习,语法简洁,易学,但执行速度和内存管理有瓶颈。

PHP的目的:构建动态网站PHP的目的:构建动态网站Apr 15, 2025 am 12:18 AM

PHP用于构建动态网站,其核心功能包括:1.生成动态内容,通过与数据库对接实时生成网页;2.处理用户交互和表单提交,验证输入并响应操作;3.管理会话和用户认证,提供个性化体验;4.优化性能和遵循最佳实践,提升网站效率和安全性。

PHP:处理数据库和服务器端逻辑PHP:处理数据库和服务器端逻辑Apr 15, 2025 am 12:15 AM

PHP在数据库操作和服务器端逻辑处理中使用MySQLi和PDO扩展进行数据库交互,并通过会话管理等功能处理服务器端逻辑。1)使用MySQLi或PDO连接数据库,执行SQL查询。2)通过会话管理等功能处理HTTP请求和用户状态。3)使用事务确保数据库操作的原子性。4)防止SQL注入,使用异常处理和关闭连接来调试。5)通过索引和缓存优化性能,编写可读性高的代码并进行错误处理。

您如何防止PHP中的SQL注入? (准备的陈述,PDO)您如何防止PHP中的SQL注入? (准备的陈述,PDO)Apr 15, 2025 am 12:15 AM

在PHP中使用预处理语句和PDO可以有效防范SQL注入攻击。1)使用PDO连接数据库并设置错误模式。2)通过prepare方法创建预处理语句,使用占位符和execute方法传递数据。3)处理查询结果并确保代码的安全性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具