PHP Basics _ PHP Tutorial

Source: Internet
Author: User
Tags php basics
Summary of the basic knowledge of PHP. Some of these PHP concepts are difficult to understand at the beginning. I listed them all in the hope that they could help some people with less thorns on the way forward. 1. variablevariables.

1. variable variables (variable)

Variable_variables.php

The code is as follows:


$ A = 'hello ';
$ Hello = 'Hello everone ';

Echo $ .'
';

$ B = 'John ';
$ C = 'Mary ';
$ E = 'job ';

$ Students = array ('B', 'c', 'E ');

Echo $ {$ students [1]};
/*
Foreach ($ students as $ seat ){
Echo $ seat .'
';
}
$ Var [1]
$ {$ Var [1]} for #1
*/

$ A = 'hello ';

Assign hello to the variable $ a, so $ a =$ {hello} = $ hello = 'Hello everone ';

For $ students [1], this can cause confusion. the interpreter of php may not be able to understand it. although '[' has a high operator, the result may not be output.

Good syntax: $ {$ students [1]} = 'Mary ';

2. array's function (array function)

Array_functions.php

The code is as follows:


Echo'

Shift & unshift

';
$ Numbers = array (1, 2, 3, 4, 5, 6 );
Print_r ($ numbers );
Echo'
';

// Shifts first elemnt out of an array
// The index will reset
$ A = array_shift ($ numbers );

Echo 'A: '. $ .'
';
Print_r ($ numbers );

// Push element to the front of array
// Returns the count of array and reset array index
$ B = array_unshift ($ numbers, 'first ');
Echo'
B: '. $ B .'
';
Print_r ($ numbers );

Echo'

';
Echo'

Pop & push

';
// Pop the last element out of array
$ C = array_pop ($ numbers );
Print_r ($ numbers );
Echo'
';

// Push the element to the last of array
$ D = array_push ($ numbers, 'last ');
Echo 'd: '. $ d .'
';

Print_r ($ numbers );



More array functions

3. dates and times (time and date)

There are three ways to create a unix time (from to the current number of seconds)

Time (); returns the current timestamp

Mktime ($ hr, $ min, $ sec, $ month, $ day, $ year); mktime (2012, 5/22,) returns the 6:30:00 timestamp.

Strtotime ($ string); strtotime ("+ 1 day") returns the timestamp of tomorrow at this time. more 'last Monday' lasy year'

Checkdate ($ month, $ day, $ year); verify whether a date is true checkdate (2012 )? 'True': 'false'; // return false

After obtaining the timestamp, we need to convert it to readable, such

We have two methods: date ($ format, $ timestamp); strftime ($ format [, $ timestamp])

2nd recommended types, strftime ("% Y-% m-% d % H: % M: % S"); // return 15:46:40

More time and date references

5. server variables (server and execution environment information)

$ _ SERVER

Server_variables.php

The code is as follows:



Echo 'server details:
';
Echo 'server _ NAME: '. $ _ SERVER ['server _ name'].'
';
Echo 'server _ ADD: '. $ _ SERVER ['server _ ADDR'].'
';
Echo 'server _ PORT: '. $ _ SERVER ['server _ port'].'
';
Echo 'document _ ROOT: '. $ _ SERVER ['document _ root'].'
';
Echo'
';

Echo 'Page details:
';
Echo 'remote _ ADDR: '. $ _ SERVER ['remote _ ADDR'].'
';
Echo 'remort _ PORT: '. $ _ SERVER ['remote _ port'].'
';
Echo 'request _ URI: '. $ _ SERVER ['request _ URI'].'
';
Echo 'query _ STRING: '. $ _ SERVER ['query _ string'].'
';
Echo 'request _ METHOD: '. $ _ SERVER ['request _ method'].'
';
Echo 'request _ TIME: '. $ _ SERVER ['request _ time'].'
';
Echo 'http _ USER_AGENT: '. $ _ SERVER ['http _ USER_AGENT'].'
';
Echo'
';



More details

6. variable_scope (the scope of the variable is global static)

Static_variables.php

The code is as follows:


Function test ()
{
$ A = 0;
Echo $;
$ A ++;
}

Test ();
Echo'
';
Test ();
Echo'
';
Test ();
Echo'
';

Echo'

';
Function test1 ()
{
Static $ a = 0;
Echo $;
$ A ++;
}

Test1 ();
Echo'
';
Test1 ();
Echo'
';
Test1 ();
Echo'
';

The variable $ a in the test () function does not save the result of $ a ++. the repeated call of test () does not increase the value of $.

The variable $ a in the test1 () function declares staic $ a = 0, which is a static variable.

Reference: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

A static variable can only exist in the local function scope, that is, the test1 () function, but when the program leaves the test1 () scope, the static variable will not lose its value, that is, the $ a variable increases by 1. when test1 () is called again, $ a = 1;

Global_variables.php

The code is as follows:


$ A = 1;
$ B = 2;

Function Sum ()
{
Global $ a, $ B;

$ B = $ a + $ B;
}

Sum ();
Echo $ B;
Echo'

';
$ A = 1;
$ B = 2;

Function Sum1 ()
{
$ GLOBALS ['B'] = $ GLOBALS ['A'] + $ GLOBALS ['B'];
}

Sum1 ();
Echo $ B;

Reference: In PHP global variables must be declared global inside a function if they are going to be used in that function

If these variables are used in the function, the global variables must be defined in the function in use. This can avoid a lot of trouble.

More details

7. reference)

Variable_reference.php

The code is as follows:


$ A = 'arist ';
$ B = $;
$ B = 'Ming ';
Echo "My name is: {$ a}. But my mother call me {$ B }.
";

Echo'

';

$ A = 'arist ';
$ B = & $;
$ B = 'Ming ';

Echo "My name is: {$ a}. And my mother call me {$ B }.
";



This concept can be understood in this way. My mom calls me Mingming, but my leaders call me Xiaoyan. whether it is Mingming or Xiaoyan, it is me.
'&' And this is a reference of the alias method called by different people, which is equivalent to $ a = {me, or a value in memory}, $ B = {lead, mom, or variable}
Through &, $ B points to the unique and identical value of $ a in the memory. So no matter what your leader calls you or what your mom calls you, you are all you. The name is different.

Therefore, after referencing, we change the value of $ B and the value of $.

8. pass reference variable to function (pass the reference parameter to the function)

The code is as follows:


Function ref_test (& $ var ){
Return $ var * = 2;
}

$ A = 10;
Ref_test ($ );
Echo $;



When we pass a parameter to a function by reference, we do not pass a copy of the variable, but a real value,

So when we call the function ref_test ($ a), the value of $ a has been changed, so the last $ a = 20;

9. reference function return value (reference function return value)

Reference_function_return_value.php

The code is as follows:


Function & increment (){
Static $ var = 0;
$ Var ++;
Return $ var;
}

$ A = & increment (); // 1
Increment (); // 2
$ A ++; // 3
Increment (); // 4
Echo "a: {$ }";



First, declare a reference function. in the function body, declare a static variable $ var to save the added value;

$ A = & increment (); this statement is the return value of the variable $ a referencing the function increment,

Like the referenced variable, you can regard the increment () function as a variable, which becomes $ a = & $ B;

Therefore, both increment () and $ a point to the same value. changing any one can change the same value.

More details

Object OOP

1. Fatal error: Using $ this when not in object context

This error is certainly easy to learn from OOP, because you do not really understand it. The class's accessibility (accessible) can also be called the scope. you can also think that a Chinese is abroad and does not belong to any culture, he does not speak a foreign language (maybe he knows something), but he cannot communicate with foreigners because they are not born in a common country.
So how does an error occur? See the following example:

The code is as follows:


Class Trones {
Static public $ fire = "I am fire .";
Public $ water = "I am water ";

Static function getFire (){
Return $ this-> fire; // wrong
}
Static function getWater (){
Return $ self: water; // wrong
}

Static function Fire (){
Return self: $ fire; // be sure you use self to access the static property before you invoke the function
}
}

/*
Fatal error: Using $ this when not in object context
*/
// Echo Trones: getFire ();
// Echo Trones: getWater ();

// Correct
Echo Trones: Fire ();
Echo"
";
$ Trones = new Trones;
$ Trones-> fire; // Notice: Undefined property: Trones: $ fire (base on defferent error setting) simple is error
Echo Trones: $ fire;

This error is classic and practical. let's first look at the definition of static:

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can ).

When defining a class's properties or methods as static, they can be directly accessed without initializing a class. A property defined as static cannot be accessed by class objects using object operators *-> * (it can be accessed through static methods ).

Example:
Line 7 and line 10 make the same mistake. The first one is to use object operators to access static variables. Let's take a look at the definition. $ this is a pseudo variable equivalent to an object and an instance. If you use the object operator> access, an error is returned.

Similarly, you cannot use the static operator: To access a public variable. The correct access should be 14 rows and 25 rows. one is to access (self ::== Trones: :) in the class definition, and the other is to access outside the class.

For inheritance classes, the above rules are also suitable.

2. Fatal error: Call to private method


Recently, there was a series of games called rights. we suppose there were three horses, Seven Kings, civilians, and Dragon Girls. The three men compete for the final victory, that is, the Crown.

The following story also has a title: class visibility. if you know the final answer, you can skip the explanation section.

The code is as follows:


Class Trones {
Protected $ fire = "fire ";
Public $ water = "water ";
Static private $ trones = "Trones ";

Protected function getFire (){
$ This-> fire;
}

Static public function TheDragenOfMather (){
Return _ METHOD _. "use". $ this-> getFire (). "gets the". self: getTrones ();
}

Static public function getWater (){
Return _ METHOD __;
}

Static private function getTrones (){
Return self: $ trones;
}

}

Class Kings extends Trones {
Static function TheSevenKing (){
Return _ METHOD _. "gets the". self: getTrones ();
}
}

Class People extends Trones {
Static function ThePeople (){
Return _ METHOD _. "gets the". self: getTrones ();
}
}
Echo Kings: TheSevenKing ();
Echo Trones: TheDragenOfMather ();
Echo People: ThePeople ();



The correct answer is: the seven countries fought in the fight, there were countless civilian deaths and injuries, and the dragon girl wanted to seize the opportunity to gain profit. Unfortunately, no one finally got the crown and victory. Haha.

When static encounters private, the combination produces complexity and beauty. it is like an abstract person, like the mathematics class that our college teachers talk about. (NetEase's public mathematics class is good)

If you want the dragon girl to win the final victory, you just need to help her remove the $ this-> getFire () section of the 13 rows. Similarly, you cannot use any object operator in a static function.

How can people get the crown? Let's go!

If you do not build large frameworks or websites, these concepts such as Interface Implement abstract... You still don't know.

Bytes. 1. variable variables (variable...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.