learning:php
Различия
Показаны различия между двумя версиями страницы.
learning:php [09.02.2018 09:33] – создано viacheslav | learning:php [30.07.2024 19:21] (текущий) – внешнее изменение 127.0.0.1 | ||
---|---|---|---|
Строка 1: | Строка 1: | ||
+ | ====== Конспект курса на Codeacademy ====== | ||
+ | https:// | ||
+ | |||
+ | Выполняется на сервере, | ||
+ | |||
+ | Your PHP code goes inside the <?php and ?> delimiters. Here we use the function echo to output I'm learning PHP!. We also end the line with a semicolon. | ||
+ | |||
+ | The echo function outputs strings. | ||
+ | <code php> | ||
+ | <?php | ||
+ | echo " | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | **Сoncatenation operator** glues several strings together. The concatenation operator is just a dot (.). | ||
+ | <code php> | ||
+ | <?php | ||
+ | echo " | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | In addition to outputting strings, PHP can also do math. Remember: no quotes around numbers! | ||
+ | <code php> | ||
+ | <?php | ||
+ | echo 5 * 7; | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | A **variable** can store a string or a number, and gives it a specific case-senstive name. All variable names in PHP start with a dollar sign ( $ ). | ||
+ | <code php> | ||
+ | <?php | ||
+ | $myName = " | ||
+ | $myAge = 32; | ||
+ | echo " | ||
+ | echo " | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | Comments use two forward slashes %%(//)%% | ||
+ | <code php> | ||
+ | <?php | ||
+ | echo "I get printed!"; | ||
+ | // I don't! I'm a comment. | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | === List of comparison operators === | ||
+ | %%>%% Greater than\\ | ||
+ | %%<%% Less than\\ | ||
+ | %%<=%% Less than or equal to\\ | ||
+ | %%>=%% Greater than or equal to\\ | ||
+ | %%==%% Equal to\\ | ||
+ | %%!=%% Not equal to | ||
+ | |||
+ | ===== If statements ===== | ||
+ | An if statement is made up of the if keyword, a condition like we've seen before, and a pair of curly braces { }. If the answer to the condition is yes, the code inside the curly braces will run. | ||
+ | <code php> | ||
+ | <?php | ||
+ | $age = 17; | ||
+ | if( $age > 16 ) { | ||
+ | echo "You can drive!"; | ||
+ | } | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | In addition to doing something when the condition is true, we can do something else if the condition is false. We can do this using an if/else statement: | ||
+ | <code php> | ||
+ | <?php | ||
+ | $name = " | ||
+ | |||
+ | if ($name == " | ||
+ | print "I know you!"; | ||
+ | } | ||
+ | else { | ||
+ | print "Who are you?"; | ||
+ | } | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | **Elseif** - it extends an **if** statement to execute a different statement in case the original **if** expression evaluates to FALSE. However, unlike **else,** it will execute that alternative expression only if the **elseif** conditional expression evaluates to TRUE. | ||
+ | <code php> | ||
+ | <? | ||
+ | $z = 2 + 3; // будет выведено слово " | ||
+ | if ($z == 4) { | ||
+ | echo " | ||
+ | } | ||
+ | elseif ($z == 5) { | ||
+ | echo " | ||
+ | } | ||
+ | else { | ||
+ | echo " | ||
+ | } | ||
+ | ?> | ||
+ | </ | ||
+ | ===== Switch statement ===== | ||
+ | A switch statement comes in handy when you have a series of if/ | ||
+ | <code php> | ||
+ | $myNum = 2; | ||
+ | |||
+ | switch ($myNum) { | ||
+ | case 1: | ||
+ | echo " | ||
+ | break; | ||
+ | case 2: | ||
+ | echo " | ||
+ | break; | ||
+ | case 3: | ||
+ | echo " | ||
+ | break; | ||
+ | default: | ||
+ | echo "None of the above"; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | === Multiple Cases. Falling Through === | ||
+ | <WRAP group> | ||
+ | <WRAP half column> | ||
+ | You sometimes want to make multiple expressions, | ||
+ | <code php> | ||
+ | if ($i == 1 || | ||
+ | $i == 2 || | ||
+ | $i == 3) { | ||
+ | echo '$i is somewhere between 1 and 3.'; | ||
+ | } | ||
+ | </ | ||
+ | </ | ||
+ | <WRAP half column> | ||
+ | With a **switch** statement, you can do this by adding **cases** right after another without a break. This is called **falling through**. The following code works exactly like the above **if** statement: | ||
+ | <code php> | ||
+ | case 1: | ||
+ | case 2: | ||
+ | case 3: | ||
+ | echo '$i is somewhere between 1 and 3.'; | ||
+ | break; | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | === Alternative syntax === | ||
+ | There' | ||
+ | <WRAP group> | ||
+ | <WRAP half column> | ||
+ | <code php> | ||
+ | switch ($i) { | ||
+ | |||
+ | } | ||
+ | </ | ||
+ | </ | ||
+ | <WRAP half column> | ||
+ | <code php> | ||
+ | switch ($i): | ||
+ | |||
+ | endswitch; | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | ===== Array ===== | ||
+ | An array is a list of items, a bit like a shopping list. It allows you to store more than one item in only one variable. An array starts in the same way as a variable, with the $ sign, and then a name, followed by =. However, this is when things start to get different. When declaring an array, we have to use // | ||
+ | <code php> | ||
+ | <?php | ||
+ | | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | <WRAP group> | ||
+ | <WRAP half column> | ||
+ | Each item in an array is numbered starting from 0. We can access a particular item of the array using its position. | ||
+ | <code php> | ||
+ | <?php | ||
+ | $myArray = array(" | ||
+ | |||
+ | echo $myArray[0] // outputs " | ||
+ | ?> | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | <WRAP half column> | ||
+ | When accessing arrays by offset, you can actually use two different types of syntax: the [ ] syntax we've covered, or you can use curly braces ({ }). You use the curly braces just like you use the square brackets: | ||
+ | <code php> | ||
+ | <?php | ||
+ | | ||
+ | print $myArray{2}; | ||
+ | ?> | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | An item in an array can be changed by specifying its position and providing a new value. | ||
+ | <code php> | ||
+ | <?php | ||
+ | $myArray = array(" | ||
+ | |||
+ | echo $myArray[1]; | ||
+ | // outputs " | ||
+ | |||
+ | $myArray[1] = " | ||
+ | |||
+ | echo $myArray[1]; | ||
+ | // outputs " | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | Finally, you can remove elements using //unset:// | ||
+ | <code php> | ||
+ | <?php | ||
+ | $array = array(" | ||
+ | unset($array[2]); | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | You can even delete the whole array: | ||
+ | <code php> | ||
+ | <?php | ||
+ | unset($array); | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | ===== Loop ===== | ||
+ | A loop is a useful bit of code that repeats a series of instructions for you. | ||
+ | ==== " | ||
+ | **For** loops are great for running the same code over and over, especially when you know ahead of time how many times you'll need to loop. | ||
+ | |||
+ | Instead of using echo (list of leap years) | ||
+ | <code php> | ||
+ | <?php | ||
+ | echo 2004; | ||
+ | echo 2008; | ||
+ | echo 2012; | ||
+ | // And so on | ||
+ | ?> | ||
+ | </ | ||
+ | we can use | ||
+ | <code php> | ||
+ | <? | ||
+ | for ($leap = 2004; $leap < 2050; $leap = $leap + 4) { | ||
+ | echo "< | ||
+ | } | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | $i++ is shorthand for $i = $i + 1. You'll see this a lot! | ||
+ | <code php> | ||
+ | <?php | ||
+ | for ($i = 0; $i < 10; $i++) { | ||
+ | echo $i; | ||
+ | } | ||
+ | // echoes 0123456789 | ||
+ | ?> | ||
+ | </ | ||
+ | ==== " | ||
+ | The **foreach** loop is used to iterate over each element of an object—which makes it perfect for use with arrays! You can think of **foreach** as jumping from element to element in the array and running the code between **{ }s** for each of those elements. | ||
+ | <code php> | ||
+ | <?php | ||
+ | $langs = array(" | ||
+ | " | ||
+ | " | ||
+ | // Between the parentheses, | ||
+ | // "For each thing in $langs, assign that thing temporarily to the variable $lang." | ||
+ | foreach ($langs as $lang) { | ||
+ | echo "< | ||
+ | } | ||
+ | |||
+ | unset($lang); | ||
+ | ?> | ||
+ | </ | ||
+ | ==== " | ||
+ | A **for** loop can allow for a set number of loop iterations. But what about a situation where (due to randomness, perhaps) you don't know how many times the loop should repeat? In that case, you can use a **while** loop. A **while** loop will execute as long as a certain condition is true. | ||
+ | <code php> | ||
+ | <?php | ||
+ | // | ||
+ | $kk = 1; | ||
+ | | ||
+ | while ($kk <= 10) { | ||
+ | echo " | ||
+ | $kk ++; | ||
+ | } | ||
+ | ?> | ||
+ | </ | ||
+ | It is important when writing loops to make sure that the loop will exit at some point. The following loop will never exit and is an example of an infinite loop. | ||
+ | <code php> | ||
+ | while(2 > 1){ | ||
+ | // Code | ||
+ | } | ||
+ | </ | ||
+ | <WRAP round important 60%> | ||
+ | Avoid infinite loops like the plague! | ||
+ | </ | ||
+ | |||
+ | PHP offers the following alternative syntax for **while** loops: | ||
+ | <code php> | ||
+ | while(cond): | ||
+ | // looped statements go here | ||
+ | endwhile; | ||
+ | </ | ||
+ | When they are embedded in HTML, loops that use this // | ||
+ | ==== " | ||
+ | A **while** loop checks the loop condition __before__ each iteration of the code inside. A **do/ | ||
+ | This means that the loop condition can depend exclusively on code within the loop's body. This is the case for the code in the editor where each iteration represents a coin flip, and any time the result of the coin flip is tails, the loop stops. | ||
+ | <WRAP group> | ||
+ | <WRAP half column> | ||
+ | <wrap hi> | ||
+ | <code php> | ||
+ | <?php | ||
+ | // keep flipping a coin | ||
+ | // as long as the result is heads! | ||
+ | $flipCount = 0; | ||
+ | do { | ||
+ | $flip = rand(0,1); | ||
+ | $flipCount ++; | ||
+ | if ($flip){ | ||
+ | echo "< | ||
+ | } | ||
+ | else { | ||
+ | echo "< | ||
+ | } | ||
+ | } while ($flip); | ||
+ | $verb = " | ||
+ | $last = " | ||
+ | if ($flipCount == 1) { | ||
+ | $verb = " | ||
+ | $last = " | ||
+ | } | ||
+ | echo "< | ||
+ | ?> | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | <WRAP half column> | ||
+ | .css: | ||
+ | <code css> | ||
+ | .coin { | ||
+ | height: 50px; | ||
+ | width: 50px; | ||
+ | border-radius: | ||
+ | background-color: | ||
+ | text-align: | ||
+ | font-weight: | ||
+ | font-family: | ||
+ | color: white; | ||
+ | margin: 10px; | ||
+ | display: inline-block; | ||
+ | line-height: | ||
+ | font-size: 20px; | ||
+ | } | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | ===== Functions ===== | ||
+ | Functions are reusable pieces of code that you can use throughout an application, | ||
+ | ==== String functions ==== | ||
+ | **strlen()** is one of the most common String functions in PHP. You pass it a string, or variable containing a string, and it returns the number of characters in that string. | ||
+ | <code php> | ||
+ | <?php | ||
+ | // выведет цифру 5 | ||
+ | $length = strlen(" | ||
+ | print $length; | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | **substr()** allows you to return a substring (piece of) of your string. You pass this function the string you want to get a substring of, the character in your string to start at, and how many characters you want after your starting point. | ||
+ | |||
+ | Two other very useful string functions are **strtoupper()** and **strtolower(), | ||
+ | <code php> | ||
+ | <?php | ||
+ | $n=" | ||
+ | |||
+ | $p=substr($n, | ||
+ | echo " | ||
+ | $p2=substr($n, | ||
+ | echo " | ||
+ | |||
+ | $u=strtoupper($p); | ||
+ | echo $u | ||
+ | |||
+ | $l=strtolower($p2); | ||
+ | echo $l | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | <WRAP group> | ||
+ | <WRAP half column> | ||
+ | **strpos()** find the position of the first occurrence of a substring in a string. | ||
+ | <code php> | ||
+ | strpos(" | ||
+ | strpos(" | ||
+ | strpos(" | ||
+ | strpos(" | ||
+ | </ | ||
+ | </ | ||
+ | <WRAP half column> | ||
+ | It returns either the index of the first character, or false if nothing can be found. | ||
+ | <code php> | ||
+ | if (strpos(" | ||
+ | print " | ||
+ | } | ||
+ | // prints the " | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | ==== Math functions ==== | ||
+ | The most common Math function you'll use is **round().** This function rounds floating point numbers (numbers with decimal points in them) up or down. You can use **round()** to round your number to an integer, or to round off complex floating point numbers to a specific number of decimal places. This is accomplished by passing a second, optional parameter to **round(), | ||
+ | <code php> | ||
+ | // Round pi down from 3.1416... | ||
+ | $round = round(M_PI); | ||
+ | print $round; | ||
+ | |||
+ | // This time, round pi to 4 places | ||
+ | $round_decimal = round(M_PI, 4); | ||
+ | print $round_decimal; | ||
+ | </ | ||
+ | |||
+ | A very common and useful function is **rand().** This function returns a random number between two numbers. Optionally, you can provide your min and max numbers as parameters. | ||
+ | <code php> | ||
+ | // prints a number between 0 and 32767 | ||
+ | print rand(); | ||
+ | |||
+ | // prints a number between 1 and 10 | ||
+ | print rand(1,10); | ||
+ | </ | ||
+ | |||
+ | <wrap hi> | ||
+ | |||
+ | Create a new variable $name and store your name in it. Then print a random character from your name. Use your knowledge of strlen(string), | ||
+ | |||
+ | HINT: Remember that substr() treats characters in a string as a zero-indexed array (first letter is at position zero). This means that the last character in the string will be at position length - 1. Remember that rand() accepts 2 arguments: min and max. The last character in your name is at position strlen($name) - 1. Remember that substr() accepts 3 arguments: string, starting position, and number of characters to return. | ||
+ | <code php> | ||
+ | <?php | ||
+ | // Use your knowledge of strlen(), substr(), and rand() to | ||
+ | // print a random character from your name to the screen. | ||
+ | $name=" | ||
+ | $rl = $name[rand(0, | ||
+ | echo $rl; | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | ==== Array functions ==== | ||
+ | Arrays are a very common thing to use in programming. In fact, **array()** is actually a function! Good job, you have already used an array function. Aside from the **array()** function itself, **array_push()** is arguably the most common and useful function for manipulating arrays. **array_push()** takes two arguments: an array, and an element to add to the end of that array. | ||
+ | |||
+ | Another cool array function is **count().** Passing an array to **count()** will return the number of elements in that array. | ||
+ | <code php> | ||
+ | <?php | ||
+ | $a=array(); | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | foreach ($a as $m) { | ||
+ | echo " | ||
+ | } | ||
+ | echo "There are " . count($a) . " elements overall"; | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | Задание: | ||
+ | <code php> | ||
+ | <?php | ||
+ | // Создать массив и засунуть туда имена | ||
+ | $a=array(); | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | array_push($a, | ||
+ | // Сортировка | ||
+ | sort($a); | ||
+ | // Извлечь из массива одно значение, | ||
+ | $w=$a[rand(0, | ||
+ | // | ||
+ | echo strtoupper($w); | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | ==== Function Syntax ==== | ||
+ | The typical structure of a function is as follows: | ||
+ | <code php> | ||
+ | function name(parameters) { | ||
+ | statement; | ||
+ | } | ||
+ | |||
+ | // Пример | ||
+ | // Here we define the function... | ||
+ | function helloWorld() { | ||
+ | echo "Hello world!"; | ||
+ | } | ||
+ | // ...and here we call it! | ||
+ | helloWorld(); | ||
+ | </ | ||
+ | - The keyword // | ||
+ | - //name// indicates the name of a function, which is case insensitive. The name of a function can contain numbers, letters, underscores or dashes. | ||
+ | - The // | ||
+ | - And of course, the // | ||
+ | |||
+ | ==== The Return Keyword ==== | ||
+ | Instead of printing something to the screen, what if you want to make it the value that the function outputs so it can be used elsewhere in your program? In PHP, the //return// keyword does just that. It returns to us a value that we can work with. The difference between this and //echo// or print is that it doesn' | ||
+ | |||
+ | Think of it like a calculator solving a mathematical problem that takes several steps to complete. The value from each step is computed, but we don't see the result until we get the final answer. In other words, each value is // | ||
+ | |||
+ | ==== Parameters and Arguments ==== | ||
+ | Functions wouldn' | ||
+ | <code php> | ||
+ | function squareValue($number) { | ||
+ | echo $number * $number; | ||
+ | } | ||
+ | |||
+ | $n = 6; | ||
+ | squareValue($n); | ||
+ | </ | ||
+ | |||
+ | The function // | ||
+ | |||
+ | You can also use multiple parameters as long as they are separated by commas. | ||
+ | |||
+ | ===== Objects in PHP ===== | ||
+ | |||
+ | |||
+ | |||
+ | PHP is an object-oriented programming language, which means that you can create objects, which can contain variables and functions. | ||
+ | |||
+ | When talking about objects, you refer to variables belonging to these objects as properties (or attributes or fields), and functions are called methods. | ||
+ | |||
+ | These objects are essential when dealing with PHP, as almost everything is an object: for example, functions or arrays are objects, too! | ||
+ | And this shows why we use objects: we can bundle our functions and data in one place, we can create objects easily using classes (object constructors), | ||
+ | |||
+ | There is a //Person// **class** and one **instance** stored in //$me// on line 32. Then the greet() method of the $me object is called and the result is //echo//d on line 35. Then the stylesheet adds some color to the result. :-) | ||
+ | |||
+ | Try to understand the code. (Don't worry if some of it is tricky — we'll go over it!) | ||
+ | <code php> | ||
+ | <?php | ||
+ | // The code below creates the class | ||
+ | class Person { | ||
+ | // Creating some properties (variables tied to an object) | ||
+ | public $isAlive = true; | ||
+ | public $firstname; | ||
+ | public $lastname; | ||
+ | public $age; | ||
+ | | ||
+ | // Assigning the values | ||
+ | | ||
+ | $this-> | ||
+ | $this-> | ||
+ | $this-> | ||
+ | } | ||
+ | | ||
+ | // Creating a method (function tied to an object) | ||
+ | public function greet() { | ||
+ | return " | ||
+ | } | ||
+ | } | ||
+ | | ||
+ | // Creating a new person called " | ||
+ | $me = new Person(' | ||
+ | | ||
+ | // Printing out, what the greet method returns | ||
+ | echo $me-> | ||
+ | ?> | ||
+ | </ | ||
+ | |||
+ | ==== Objects in Real Life ==== | ||
+ | How object-oriented programming is used in real life can be shown with a forum as an example: | ||
+ | |||
+ | Every forum //user// (object) has the same rights: he can //log in// and //write// (methods), can contain some // | ||
+ | |||
+ | Every user is created easily, as you create a new **instance** of a //User// **class** when you sign up. And as we've seen, there are some properties and methods that every instance has in common (such as logging in and writing), and there are some which are unique (such as each user's name). | ||
+ | |||
+ | And without object-oriented programming—**OOP** for short—this could not be done that easily. ;-) | ||
+ | |||
+ | Another example: on the above, there is a Person class, so every new Person has some properties, like $isAlive or $firstname, and a method greet(). | ||
+ | |||
+ | Right now there is only one instance of the Person class: $me. But we'll reconstruct this class and you'll even create another instance of the class, so your name will be echod, too. | ||
+ | |||
+ | In the next exercises we are going to create some classes, so let's start coding. :-) | ||
+ | |||
+ | ==== Building Your First Class ==== | ||
+ | Great, now you know the technical terms. :-) Let's start coding by reconstructing the //Person// class. | ||
+ | |||
+ | The basic class syntax looks like the following: | ||
+ | <code php> | ||
+ | class Classname { | ||
+ | |||
+ | } | ||
+ | </ | ||
+ | The //class// keyword means that you create a new //class;// the syntax is quite similar to the // | ||
+ | |||
+ | And you can create new instances of this class using the following syntax: | ||
+ | <code php> | ||
+ | $obj1 = new Classname(); | ||
+ | </ | ||
+ | The //new// keyword means that you create a //new// object and ensures that your arguments are added as properties, so it initializes the // | ||
+ | |||
+ | We don't need to pass in any arguments, as we haven' | ||
+ | |||
+ | |||