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.

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP에서는 클론 키워드를 사용하여 객체 사본을 만들고 \ _ \ _ Clone Magic 메소드를 통해 클로닝 동작을 사용자 정의하십시오. 1. 복제 키워드를 사용하여 얕은 사본을 만들어 객체의 속성을 복제하지만 객체의 속성은 아닙니다. 2. \ _ \ _ 클론 방법은 얕은 복사 문제를 피하기 위해 중첩 된 물체를 깊이 복사 할 수 있습니다. 3. 복제의 순환 참조 및 성능 문제를 피하고 클로닝 작업을 최적화하여 효율성을 향상시키기 위해주의를 기울이십시오.

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

HTTP 캐시 헤더의 주요 플레이어에는 캐시 제어, ETAG 및 최종 수정이 포함됩니다. 1. 캐시 제어는 캐싱 정책을 제어하는 데 사용됩니다. 예 : 캐시 제어 : Max-AGE = 3600, 공개. 2. ETAG는 고유 식별자를 통해 리소스 변경을 확인합니다. 예 : ETAG : "686897696A7C876B7E". 3. Last-modified는 리소스의 마지막 수정 시간을 나타냅니다. 예 : 마지막으로 변형 : Wed, 21oct201507 : 28 : 00GMT.

PHP에서 Password_hash 및 Password_Verify 기능을 사용하여 보안 비밀번호 해싱을 구현해야하며 MD5 또는 SHA1을 사용해서는 안됩니다. 1) Password_hash는 보안을 향상시키기 위해 소금 값이 포함 된 해시를 생성합니다. 2) Password_verify 암호를 확인하고 해시 값을 비교하여 보안을 보장합니다. 3) MD5 및 SHA1은 취약하고 소금 값이 부족하며 현대 암호 보안에는 적합하지 않습니다.

PHP는 동적 웹 개발 및 서버 측 응용 프로그램에 사용되는 서버 측 스크립팅 언어입니다. 1.PHP는 편집이 필요하지 않으며 빠른 발전에 적합한 해석 된 언어입니다. 2. PHP 코드는 HTML에 포함되어 웹 페이지를 쉽게 개발할 수 있습니다. 3. PHP는 서버 측 로직을 처리하고 HTML 출력을 생성하며 사용자 상호 작용 및 데이터 처리를 지원합니다. 4. PHP는 데이터베이스와 상호 작용하고 프로세스 양식 제출 및 서버 측 작업을 실행할 수 있습니다.

PHP는 지난 수십 년 동안 네트워크를 형성했으며 웹 개발에서 계속 중요한 역할을 할 것입니다. 1) PHP는 1994 년에 시작되었으며 MySQL과의 원활한 통합으로 인해 개발자에게 최초의 선택이되었습니다. 2) 핵심 기능에는 동적 컨텐츠 생성 및 데이터베이스와의 통합이 포함되며 웹 사이트를 실시간으로 업데이트하고 맞춤형 방식으로 표시 할 수 있습니다. 3) PHP의 광범위한 응용 및 생태계는 장기적인 영향을 미쳤지 만 버전 업데이트 및 보안 문제에 직면 해 있습니다. 4) PHP7의 출시와 같은 최근 몇 년간의 성능 향상을 통해 현대 언어와 경쟁 할 수 있습니다. 5) 앞으로 PHP는 컨테이너화 및 마이크로 서비스와 같은 새로운 도전을 다루어야하지만 유연성과 활발한 커뮤니티로 인해 적응력이 있습니다.

PHP의 핵심 이점에는 학습 용이성, 강력한 웹 개발 지원, 풍부한 라이브러리 및 프레임 워크, 고성능 및 확장 성, 크로스 플랫폼 호환성 및 비용 효율성이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 웹 서버와 우수한 통합 및 여러 데이터베이스를 지원합니다. 3) Laravel과 같은 강력한 프레임 워크가 있습니다. 4) 최적화를 통해 고성능을 달성 할 수 있습니다. 5) 여러 운영 체제 지원; 6) 개발 비용을 줄이기위한 오픈 소스.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

드림위버 CS6
시각적 웹 개발 도구
