PHP

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Write an if/elseif/else statement inside the editor and make it output anything you wish.

<?php $a = 5; if($a<3){ echo"good "; } elseif($a>9){ echo"great "; } else{ echo"excellent! "; } ?>

array:

<?php $array = array("Egg", "Tomato", "Beans"); ?>

If we want the "7 of Diamonds" string, we would simply use $deck[2][0];.

<?php $deck = array(array('2 of Diamonds', 2), array('5 of Diamonds', 5), array('9 of Diamonds', 4), array('7 of Diamonds', 7)); // Imagine the first chosen card was the 7 of Diamonds. // This is how we would show the user what they have: echo 'You have the ' . $deck[2][0] . '!'; ?>

Deleting Array Elements

Finally, you can remove elements using unset: <?php $array = array("red", "blue", "green"); unset($array[2]); ?> You can even delete the whole array: <?php unset($array); ?>

switch eg

switch ($fruit) { case 'Apple': echo "Yummy."; break; case'Pear': echo "Ohhh"; break; Default: echo"kkkk"; } ?>

concatenation operator: The concatenation operator is just a dot (.)

concatenation operator: The concatenation operator is just a dot (.)

Construct eg Add a constructor to Person with three parameters, $firstname, $lastname and $age. In your constructor, use the three parameters to set the publicproperties $firstname, $lastnameand $age. Change your $teacherinstantiation to store newPerson("boring", "12345", 12345). Add your $firstname, $lastnameand $age to $student in the same manner. echo the $age of $student.

<?php class person{ public $isAlive=true; public $firstname; public $lastname; public $age; public function __construct($firstname, $lastname, $age){ $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; } } $student = new person("boring", "12345", 12345); $teacher = new person("boring", "12345", 12345); echo $student->age; ?>

while

A loop is a structure that tells a computer to execute a set of statements multiple times. If you have a process that you want repeated hundreds of times, it pays to put it in a loop so you don't need to write hundreds of lines of code. If you are working on these courses in order, you have already seen how 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. For example, the loop in the editor will simulate coin flips as long as the number of consecutive heads is less than 3.

rand()

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, like this: // prints a number between 0 and 32767 print rand(); // prints a number between 1 and 10 print rand(1,10);

sort() rsort()

Another common thing to do with arrays is sort them. Handily enough, PHP has a sort() function for just such an occasion! $array = array(5, 3, 7, 1); sort($array); print join(", ", $array); // prints "1, 3, 5, 7" PHP also has the opposite function: rsort(). $array = array(5, 3, 7 ,1); rsort($array); print join(":", $array); // prints "7:5:3:1" Lastly, we use join(glue, array) so we can easily print out the representations of our sorted arrays in this exercise.

count()

Another cool array function is count(). Passing an array to count() will return the number of elements in that array. Like this: print count($fav_bands); // prints 5

String Functions I

Another very common string function is substr(). This function 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. An example might be: $myname = "David"; // you can manipulate strings easily // with built-in funtions too $partial = substr($myname, 0, 3); print $partial; // prints "dav" 3means the lenth of substr NOTE: the second parameter (the starting character) is based on a zero-indexed array (i.e. the first character in your string is number 0, not number 1).

array_push()

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. Here's an example: $fav_bands = array(); array_push($fav_bands, "Maroon 5"); array_push($fav_bands, "Bruno Mars"); array_push($fav_bands, "Nickelback"); array_push($fav_bands, "Katy Perry"); array_push($fav_bands, "Macklemore");

Inheritance

As you've been thinking about classes and objects, you might have realized that one class might actually be a specialized type of another class. For instance, you might have a Vehicleclass and a Truck class, and it would probably save you an awful lot of typing if you could somehow specify that Truck instances should automatically have many of the same properties and methods as Vehicleinstances. PHP allows us to accomplish this through a process called inheritance. Inheritance is a way for one class to take on the properties or methods of another class. You could say that the one class extends the other. This is used to express an "is-a" relationship—for example, a Truck "is-a" Vehicle, so it could inherit from Vehicle, but a Motorcycle isn't a Truck, so it shouldn't inherit from Truck (though both could inherit from Vehicle). We can cause one PHP class to inherit from another with the extendskeyword.

Function Refresher

Don't Repeat Yourself! This is a very simple, yet fundamental principle in programming. Whenever you feel the need to rewrite a block of code, remember that it can probably be written as a function instead. You've seen some of PHP's built-in functions, but you can also define your own! By using one function instead of several blocks of the same code, you can reduce the amount of clutter in your document and keep your code neat and tidy.

Parameters and Arguments

Functions wouldn't be nearly as useful if they weren't able to take in some input. This is where parameters or arguments come in. These are the variables or inputs that a function uses to perform calculations. function squareValue($number) { echo $number * $number; } $n = 6; squareValue($n); // echos 36 The function squareValue, above, takes one parameter, which it multiplies by itself and then echos the result. The names of the parameters themselves are used internally within the function, so they should be named something helpful. You can also use multiple parameters as long as they are separated by commas.

Putting It All Together

Great work! You've learned a lot so far, including: Useful object and class methods, like property_exists() and method_exists(); Inheritance; How child classes can override the behavior of their parents; How parent classes can prevent this with the final keyword; What class constants are and how to reach them using the scope resolution operator, ::; How to access class methods and properties without creating an instance of the class by using the static keyword and the scope resolution operator together. Let's put all our newfound knowledge to work in one final (pun intended) exercise!

PHP code can be written right into your HTML, use echo to print, end your line with a semicolon.

In addition to outputting strings, PHP can also do math.

Completing the Loop

In the previous exercise, you saw how a do/while could be used to ensure that the code in a loop executed at least once. For example: <?php $i = 0; do { echo $i; } while ($i > 0); ?> This do / while loop only runs once and then exits: First we set $i equal to 0. Second, the loop runs once and outputs $i, which is 0. Then the condition while ($i > 0); is checked. Since $i is not greater than 0, the condition evaluates to false, and thedo/while` loop stops.

Math Functions round()

Let's move on to a bit of arithmetic. 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(), telling it how many decimal places you want the number rounded to.

Two other very useful string functions are strtoupper() and strtolower(), which make your entire string UPPERCASE or lowercase. Here is an example of each:

$uppercase = strtoupper($myname); print $uppercase; // prints "DAVID" $lowercase = strtolower($uppercase); print $lowercase; // prints "david" You can also call these functions on a string directly, like so: print strtolower("David"); // prints "david"

On line 8, set $fruits equal to an array of three strings: 'bananas', 'apples' and 'pears'. Modify the echo statement on line 9 to display the fruit in the middle of the array (that is, it should echo"apples".

<?php $fruits = array("bananas","apples","pears"); /* Your code here! */ echo 'I love eating ' . $fruits[1] . ' too!'; ?>

We are going to flip a coin until we get three heads in a row!

<?php $headCount = 0; $flipCount = 0; while ($headCount < 3) { $flip = rand(0,1); $flipCount ++; if ($flip){ $headCount ++; echo "<div class=\"coin\">H</div>"; } else { $headCount = 0; echo "<div class=\"coin\">T</div>"; } } echo "<p>It took {$flipCount} flips!</p>"; ?>

Multiple Cases. Falling Through! With a switch statement, you can do this by adding cases right after another without a break. This is called falling through.

<?php $i = 5; switch ($i) { case 0: echo '$i is 0.'; break; case 1: case 2: case 3: case 4: case 5: echo '$i is somewhere between 1 and 5.'; break; case 6: case 7: echo '$i is either 6 or 7.'; break; default: echo "I don't know how much \$i is."; } ?>

Loops + Arrays = ForEach

<?php $langs = array("JavaScript", "HTML/CSS", "PHP", "Python", "Ruby"); foreach ($langs as $lang) { echo "<li>$lang</li>"; } unset($lang); ?>

Complete do/while eg

<?php $loopCond = false; do { echo "<p>The loop ran even though the loop condition is false.</p>";} while ($loopCond); echo "<p>Now the loop is done running.</p>"; ?>

While eg

<?php $loopCond = true; while($loopCond == true){ //Echo your message that the loop is running below echo "<p>The loop is running.</p>"; $loopCond = false; } echo "<p>And now it's done.</p>"; ?>

Else

<?php $name = "Edgar"; if ($name == "Simon") { print "I know you!"; } else { print "Who are you?"; } ?>

foreach eg

<?php $yardlines = array("The 50... ", "the 40... ", "the 30... ", "the 20... ", "the 10... "); // Write your foreach loop below this line foreach($yardlines as $s){ echo $s; } unset ($s); // Write your foreach loop above this line echo "touchdown!"; ?>

array eg

<?php // Add your array elements after // "Beans" and before the final ")" $array = array("Egg", "Tomato", "Beans","Chips","Sausage"); ?>

array_push() count() eg

<?php // Create an array and push 5 elements on to it, then // print the number of elements in your array to the screen $a = array(); array_push($a,"1"); array_push($a,"2"); array_push($a,"3"); array_push($a,"4"); array_push($a,"5"); echo count($a); ?>

Array 汇总eg

<?php // Create an array and push on the names // of your closest family and friends $array = array("addd","bfff","cggg","dkk"); array_push($array,"huhuhuh"); // Sort the list sort($array); // Randomly select a winner! $t = count($array); $s = rand(0,$t); $r = $array[$s]; print strtoupper($r); // Print the winner's name in ALL CAPS ?>

Create a variable called $myArrayand set it equal to a new array that you create, which can contain any items you like. Grab a value from your array and display it. Now loop through the array and output the contents to the browser!

<?php // On the line below, create your own associative array: $myArray = array('ha'=>1, 'haa'=>2, 'haaa'=>3, 'haaa'=>5); // On the line below, output one of the values to the page: echo $myArray['haaa']; // On the line below, loop through the array and output foreach($myArray as $q=>$w){ echo $q,$w,'</br>','<p></p>'; } // *all* of the values to the page: ?>

Objects in Real Life

<?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 public function __construct($firstname, $lastname, $age) { $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; } // Creating a method (function tied to an object) public function greet() { return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)"; } } // Creating a new person called "boring 12345", who is 12345 years old ;-) $me = new Person('boring', '12345', 12345); // Printing out, what the greet method returns echo $me->greet(); ?>

What's Object-Oriented Programming?

<?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 public function __construct($firstname, $lastname, $age) { $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; } // Creating a method (function tied to an object) public function greet() { return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)"; } } // Creating a new person called "boring 12345", who is 12345 years old ;-) $me = new Person('boring', '12345', 12345); // Printing out, what the greet method returns echo $me->greet(); ?>

Using Arrays as Maps

<?php // This is an array using integers as the indices. // Add 'BMW' as the last element in the array! $car = array(2012, 'blue', 5,'BMW'); // This is an associative array. // Add the make => 'BMW' key/value pair! $assocCar = array('year' => 2012, 'colour' => 'blue', 'doors' => 5, 'make' => 'BMW'); // This code should output "BMW"... echo $car[3]; echo '<br />'; // ...and so should this! echo $assocCar['make']; ?>

上一页的例子

<?php // This is an array using integers as the indices... $myArray = array(2012, 'blue', 5); // ...and this is an associative array: $myAssocArray = array('year' => 2012, 'colour' => 'blue', 'doors' => 5); // This code will output "blue"... echo $myArray[1]; echo '<br />'; // ... and this will also output "blue"! echo $myAssocArray['colour']; ?>

Using the arrays from the previous exercises, write an echo statement on line 22 to talk about your car (beyond the fact that it's blue). Try using both arrays to describe the car. Which one makes it easier?

<?php // This is an array using integers as the indices... $myArray = array(2012, 'blue', 5, 'BMW'); // ...and this is an associative array: $myAssocArray = array('year' => 2012, 'colour' => 'blue', 'doors' => 5, 'make' => 'BMW'); // This code will output "blue". echo $myArray[1]; echo '<br />'; echo $myAssocArray['year']; ?>

rand() eg

<?php // Use your knowledge of strlen(), substr(), and rand() to // print a random character from your name to the screen. $str = "sarah"; $k = Strlen("sarah"); $i = rand(0,$k-1); $a = substr("$str",$i,1); print $a; ?>

Writing Your First 'For' Loop 一段范围之内

<?php // Write your for loop below! for ($i=0;$i<=100;$i=$i+10){ echo $i; } ?>

while eg

<?php //Add while loop below $a=5; while($a<100){ echo "<p>$a</p>"; $a++; } ?>

Let's create a Cat class, which has two public properties: an $isAliveproperty storing the value true and a $numLegs property containing the value 4. There should be a public $nameproperty, which should get a value when a new object is created, so assign the value to $name via the __construct() method. Then I also want these Cats to be able to meow, so add a meow()method, which returns "Meow meow". Finally, create an instance of the Catclass, which has the $name "CodeCat"and store it in the variable $cat1. Then call the meow() method on this cat.

<?php class Cat{ public $isAlive = true; public $numLegs = 4; public $name; public function __construct($name){ $this->name = $name; } public function meow(){ return"Meow meow"; } } $cat1 = new Cat("CodeCat"); echo $cat1->meow(); ?>

Add a public method to the Dogclass called bark(), which returns "Woof!". Add a public method called greet() to the Dog class. This method ought to return a nice sentence containing the $nameproperty of the Dog, which introduces himself. Create two instances of the Dogclass and store the one with the $name "Barker" in the variable $dog1 and the other one with the $name "Amigo" in the variable $dog2. As you might have expected, call the bark() method on $dog1 and echo the result. The last one: Call the greet()method on $dog2 and echo the result.

<?php class Dog{ public $numLegs =4; public $name; public function __construct($name){ $this->name = $name; } public function bark(){ return"Woof"; } public function greet(){ return"my name is $name" } } $dog1 = new Dog("Barker"); $dog2 = new Dog("Amigo"); echo $dog1->bark(); echo $dog2->greet(); ?>

At last we'll need two cute dogs. :-)

<?php class Dog{ public $numLegs =4; public $name; public function __construct($name){ $this->name = $name; } public function bark(){ } public function greet(){ } } ?>

We've created a King class with a proclaim() method in the editor to the right. Go ahead and call the proclaim() method using the static keyword—no instances necessary!

<?php class King { // Modify the code on line 10... static public function proclaim() { echo "A kingly proclamation!"; } } // ...and call the method below! king::proclaim(); ?>

We've created the Ninja class for you in the editor. Set a stealth constant to the string "MAXIMUM". Then echo it to the page using Ninja::stealth. That :: is the scope resolution operator.

<?php class Person { } class Ninja extends Person { // Add your code here... const stealth="MAXIMUM"; } // ...and here! if (Ninja::stealth){ echo"MAXIMUM"; } ?>

Class and Object Methods

<?php class Person { public $isAlive = true; function __construct($name) { $this->name = $name; } public function dance() { return "I'm dancing!"; } } $me = new Person("Shane"); if (is_a($me, "Person")) { echo "I'm a person, "; } if (property_exists($me, "name")) { echo "I have a name, "; } if (method_exists($me, "dance")) { echo "and I know how to dance!"; } ?>

Create a class called Person. It should contain only a single method, say(), that should take no arguments and echo: `"Here are my thoughts!"; Create another class, Blogger, that inherits from Person. It should contain only a single constant, cats, set to 50. Use the static keyword and the scope resolution operator to call Blogger's inherited say() method without creating an instance of the class. Use the scope resolution operator to echo the cats constant to the page.

<?php class Person{ static public function say(){ echo "Here are my thoughts!"; } } class Blogger extends Person{ const cats = 50; } Blogger :: say(); echo Blogger :: cats; ?>

继承例子 Check out the code in the editor to the right. We've created two classes, Shape and Square, with Squareinheriting from Shape. We didn't specify that Square has a $hasSides property, but it should inherit it from Shape. Complete the if statement on line 18 by using the property_exists()method to check if $square has the "hasSides" property. Check the Hint for help!

<?php class Shape { public $hasSides = true; } class Square extends Shape { } $square = new Square(); // Add your code below! if ( property_exists($square,"hasSides")) { echo "I have sides!"; } ?>

We've created a Vehicle class in the editor. Create a child class, Bicycle, that overrides the Vehicle class' publicfunction honk() and replaces it with a function that returns "Beep beep!". Create a $bicycle instance of the Bicycle class and echo the result of calling its honk() method. Check the Hint for refreshers if you need them!

<?php class Vehicle { public function honk() { return "HONK HONK!"; } } // Add your code below! class Bicycle extends Vehicle{ public function honk(){ return "Beep beep!"; } } $bicycle = new Bicycle(); echo $bicycle->honk(); ?> </p>

Building Your First Class

<?php class person{ } $student = new person(); $teacher = new person(); ?>

Property eg Add a public $isAlive property to the Person class and assign the value true to $isAlive, like the $count property above. Add three further publicproperties to thePerson class: $firstname, $lastname and $age. Don't assign any values to these like the $type property above. echo the value of the $teacher's $isAlive property.

<?php class person{ public $isAlive=true; public $firstname; public $lastname; public $age; } $student = new person(); $teacher = new person(); echo $teacher->isAlive; ?>

Add a method called greet() to your class. This method ought to return "Hello, my name is " .$this->firstname . " " . $this->lastname . ". Nice to meet you! :-)" . Call this new greet() method on $teacher and $student and echothe result to the page.

<?php class person{ public $isAlive=true; public $firstname; public $lastname; public $age; public function __construct($firstname, $lastname, $age){ $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; } public function greet(){ echo "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)"; } } $student = new person("boringjj", "12345", 12345); $teacher = new person("boringjj", "12345", 12345); echo $student->age; echo $student->greet(); echo $teacher->greet(); ?>

Loop

<?php for ($leap = 2004; $leap < 2050; $leap = $leap + 4) { echo "<p>$leap</p>"; } ?>

Write a function called aboutMe. It takes two parameters $name and $age. It should echo out "Hello! My name is $name, and I am $age years old.".

<?php function aboutMe($name,$age){ echo "Hello! My name is $name, and I am $age years old."; } aboutMe("sarah",25); ?>

Parameters eg

<?php function greetings($name){ echo"Greetings,".$name,"!" ; } greetings("sarah") ?>

The Return Keyword 2

<?php function returnName(){ return "Sarah"; } returnName() ?>

switch: Then we have a case block for each comparison. For example case 1: echo "1"; break; checks whether $myNum is equal to 1. If yes, it echos "1", and uses break to exit the switch statement. Otherwise, the next case block runs. If all cases return false, the default case gets executed.

<?php switch (2) { case 0: echo 'The value is 0'; break; case 1: echo 'The value is 1'; break; case 2: echo 'The value is 2'; break; default: echo "The value isn't 0, 1 or 2"; } ?>

Access by Offset with [ ] Count from 0, Therefore, we can access a particular item of the array using its position, like this:

<?php $myArray = array("do", "re", "mi"); echo $myArray[0] ?> and also could use print $myArray{0}

Modifying Array Elements

<?php $myArray = array("red", "blue", "yellow"); echo $myArray[1]; // outputs "blue" $myArray[1] = "green"; echo $myArray[1]; // outputs "green" ?>

Property construct

Good job, now we have some properties. But right now $teacher and $student are the same, which should be changed immediately, correct? :-) The solution: we have to create a constructor to create different objects. This constructor is also a method, but you don't need to worry about this fact just yet. The syntax: public function __construct($prop1, $prop2) { $this->prop1 = $prop1; $this->prop2 = $prop2; } So you should remember the public keyword and the arrow notation. Some new things: You're creating a function bound to a class (a method). The constructor method has to be called __construct(). Finally, the weird way to assign the values: $this->prop1 = $prop1 means that the value you pass in the __construct() function via the new keyword is assigned to $this, which represents the object you are dealing with, and ->prop1 is the actual property of the object. By creating a new instance using the new keyword, you actually call this __construct() method, which constructs the object. And that's why we have to pass in some arguments when we create an instance of a class, since this is how the properties get set!

Method

Great work, now the hardest and longest part is behind us. :-) As you've seen, methods—functions bundled into objects—have the following syntax: public function funcname($optionalParameter) { // Do something } And now we know the __construct function is a special one, which is called when a new object is created using a new keyword. Furthermore, we've learnt we have to use the $this keyword, if we want to access some properties in a class. So if we want a method to return a sentence containing the firstname, we would have to use $this->firstname. (As you see, there is no $ when you access a property in a class.) Calling a method is similar to accessing a property, you just have to add the parentheses: $obj1 -> meth1();

Property

Great work, now we can add some properties to our class. As you remember, properties are pieces of data bound to an object, and you can imagine an object as a bundle of information and actions. class Fruit { public $count = 3; public $type; } $apple = new Fruit(); $apple->type = "apple"; print $apple->count; // 3 print $apple->type; // apple In the example above, we first create a new class called Fruit. Then we add a property, $count, and set its value to 3. Next, we add a property, $type, but don't store anything in it yet. After the class definition, we create new instance of Fruit and store it in $apple. Then we set the $type property of $apple to the string "apple". Finally, we print out the two properties of $apple.

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: class Classname { } The class keyword means that you create a new class; the syntax is quite similar to the function syntax. And you can create new instances of this class using the following syntax: $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 constructor (which we are going to deal with later). We don't need to pass in any arguments, as we haven't added any properties (which can store different values depending on the instance) quite yet.

Math Functions round()

Here's an example: // Round pi down from 3.1416... $round = round(M_PI); print $round; // prints 3 // This time, round pi to 4 places $round_decimal = round(M_PI, 4); print $round_decimal; // prints 3.1416

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 settings (properties), but every user has a different name (another property). 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 right, there is a Person class, so every new Personhas 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.

array:

However, this is when things start to get different. When declaring an array, we have to use array(). This basically tells PHP that $array is an array and not something else, such as a regular old variable.By now, I am sure you have noticed the text inside the ( and ). This is just the items in our array. So, currently, our array has the items "Egg," "Tomato," and "Beans" in it. You can add any type of information to an array, and you do it in much the same way as when declaring variables. Use "" when adding strings, and just enter the number when adding integers.You must always remember, however, that each item in an array must be separated by a comma: ,.

While Loop Syntax 给那些不造应该循环多少遍

In the last exercise, you saw how a while loop can be used to repeat a set of commands an unknown number of times. That loop used the following syntax: while(cond) { // looped statements go here } where the statements in side the curly braces { and } are executed as long as the condition cond is evaluated as true. In the last exercise, cond was the condition that the number of consecutive heads was less than 3: $headCount < 3. It is important when writing loops to make sure that the loop will exit at some point. The loop while(2 > 1){ // Code } will never exit and is an example of an infinite loop. Avoid infinite loops like the plague! This is why we need to include $loopCond = false; in line 12. If you submit an infinite loop in one of these exercises, you will need to reload the page to stop it.

Review Well done, mission accomplished. :-)

In this course you've learnt the basics of object-oriented programming, or OOP for short: You know what a class is. You know what an object is. You know that you create objects using classes, as you simply create an instance of a class to create a new object. You know how to create classes and objects. You know how to add properties to a class. You know how to add methods to a class. You know how to use the __construct() method and the newkeyword. You know the arrow notation.

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't actually display the value. 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 returned and the final answer is echoed on screen for us.

Just like we sometimes put comments in our CSS (using /* this syntax */) or in our HTML (using <!-- this syntax -->), we can also put comments in our PHP code! We do that using two forward slashes (//)

List of comparison operators: > Greater than < Less than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to

Iterating Over Associative Arrays

Looping through an associative array is just as easy as looping through a normal array, but you obtain the value from a specified key, not an integer. Just like in the previous exercises! If we only need to loop through the values of an array, we can use for. Have a look at the editor to see an example of this being used. Remember, when using a for loop, calculate the length of the array first! Then have a look at the foreach loop to see how we can get the key and value of each pair in the array.

Overriding Parent Methods

Nice work! Sometimes we want a child class (or subclass) to be able to override a property or method of its parent class (or superclass). For instance, we might have a Shape class with a $sides property set to true, but we might want Square to override this property and set $sides to 4 (since a square always has four sides). That would look something like this: class Shape { $sides = true; } class Square extends Shape { $sides = 4; } It's pretty easy—you just create a new property or method in the child class with the same name as the one in the parent class, and the child's version will always take precedence over the inherited version.

Multidimensional Arrays

Not only can you store integers and strings in arrays, you can also store... other arrays! This is called a multidimensional array. How do we do this? Well, just like a normal array with comma-separated values, but you would put comma-separated arrays instead—just like the code in the editor. $deck is an array which contains 3 rows, each being a playing card. Within each row, it has the name of the card, along with the value. To retrieve a card, we would first get the row for that card, then get the value we require (either to display the card, or calculate the player's total). If we access $deck[2], we would get the third row (remember, arrays start from 0 in PHP!) That will return another array containing 2 values: the first (0) which is a string that has the value "7 of Diamonds", and the second (1) which is an integer that has the value 7.

PHP code is written in the <?phpand ?>

PHP code is written in the <?phpand ?>

What's Object-Oriented Programming?

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), so we can create lots of instances (objects, which have been constructed via a class), which contain mostly the same data, except some little nuances. On the right, 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 echod on line 35.

Using Endwhile

PHP offers the following alternative syntax for while loops: while(cond): // looped statements go here endwhile;

Class and Object Methods

Remember when we covered built-in functions in PHP? Well, we can combine that idea with our knowledge of classes and objects: that is, there are built-in PHP functions that tell us interesting information about the classes and objects we've created! Check out the example in the editor to the right. We're demoing three useful built-in methods: is_a(), which we use to find out if a particular object is an instance of a given class; property_exists(), to see if an object has a given property; and method_exists(), to see if an object has a given method. Note that the first argument is the object we're checking, and the second is the class, property, or method name as a "string".

Associative Arrays

So far, you have been accessing the values of an array using integers. This is all well and good, but if you want to be more descriptive of your data, you can make use of something called an associative array. An associative array makes use of (key => value) pairs. Some languages may separate arrays from associative arrays, but PHP treats both as the same. In the editor, you will see I have declared two variables as arrays. Have a look at the first array and see if you can guess what item those values may refer to? Now have a look at the array below it. This is an associative array. It's defined as an array like the first one, but see how I have specified keys for each of the values? Both arrays contain the same values, but in the associative array, we can access the value using a specified "key".

Loops + Arrays = ForEach

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.对每一个数组里的元素都变成lang然后执行另一个操作 最后删除lang

Function Syntax

The typical structure of a function is as follows: function name(parameters) { statement; } The keyword function indicates that the code following it will be a user-defined function. name indicates the name of a function, which is case insensitive. The name of a function can contain numbers, letters, underscores or dashes. The arguments, or parameters, will be the optional input a function uses to perform calculations. And of course, the statements themselves will be the code the function executes when it is called.

Putting it All Together

This is the time to practice everything you've learned so far about associative arrays. Here's some quick reminders: Arrays in PHP are zero-based (this means the numeric ID of the first value in the array will always be 0, not 1). An array can contain values ("val1", "val2", etc... ) As an associative array, it can contain keys and values ("key1" => "val1", "key2" => "val2", etc... ) A multidimensional array can contain arrays within arrays! To loop through an array containing values only, you can use the for loop. For an array containing keys and values, you can use the foreach loop.

In the editor, create your own associative array and loop through the keys and values.

Try creating an array like the following: $me = array('hair' => 'black', 'skin tone' => 'light'); and you could display the values like this: foreach ($me as $feature=>$colour) { echo 'My ' . $feature . ' is ' . $colour . '. '; } <?php $food = array('pizza', 'salad', 'burger'); $salad = array('lettuce' => 'with', 'tomato' => 'without', 'onions' => 'with'); // Looping through an array using "for". // First, let's get the length of the array! $length = count($food); // Remember, arrays in PHP are zero-based: for ($i = 0; $i < $length; $i++) { echo $food[$i] . '<br />'; } echo '<br /><br />I want my salad:<br />'; // Loop through an associative array using "foreach": foreach ($salad as $ingredient=>$include) { echo $include . ' ' . $ingredient . '<br />'; } echo '<br /><br />'; // Create your own array here and loop // through it using foreach! $myarray = array('a' => '1', 'b' => '2', 'c' => '3'); foreach ($myarray as $k=>$s) { echo $k . ' ' . $s . '<br />'; } ?>

Class Constants and Scope Resolution

We've talked a lot about changing variables in PHP, but sometimes we want variables that don't change. These are prefixed with the const keyword (short for constant). PHP lets us set constants on a class-by-class basis! Each class has its own scope, which is the context in which its variables can be used. class Immortal extends Person { // Immortals never die! const alive = true; } // If true... if (Immortal::alive) { echo "I live forever!"; } // echoes "I live forever!" In the example above, we use :: to access the alive constant inside the Immortal class. Note that constants do not start with $.

Putting It All Together, Part I

Well done! You've reconstructed the Person class. Let's create another class: a Dog class. It should have a public property $numLegs, which stores the value 4. Furthermore, there should be the possibility to give every dog a $nameusing a __constructor. Of course we also need some methods, as a dog is able to bark(). Our dogs are also able to introduce themselves, to greet(), so we'll also need a method for this.

The Final Word 阻止子类重写

When you were a kid, one of your parents might have told you: "You're not doing that, and that's final!" In PHP, a parent class can prevent its methods from being overridden by its children with—you guessed it—the final keyword. You'd want to use the final keyword in your code to control what methods can be modified by a class' subclasses. For instance, you might want all Vehicles to have the same drive() method no matter what, so you would prefix its method definition with final, like so: class Vehicle { final public function drive() { return "I'm drivin' here!"; } }

Using Arrays as Maps

You can think of an associative array (also called a map) as being the same as a normal array, but instead of using an integer to refer to the value, you use a defined key. While numeric indices may be fine for looping through an array and listing all of the values, what if we need to change a certain value from an array? For each array in the editor, add the value "BMW" to the end of the array. For the associative array, use "make" as the key. You can add a key just as shown in the editor: 'key' => value (You'll see a PHP error until you add the missing array elements.)

Do-While?

You may have noticed that a whileloop checks the loop condition before each iteration of the code inside. A logical alternative is to check the condition after each iteration before looping back. A do/while loop does just that. One consequence of this difference is that the code inside a while loop can be bypassed entirely whereas the code inside a do/whileloop will execute at least once. 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.

The Static Keyword Nice work!

You probably noticed that we could access the Ninja class constant without actually creating an instance of Ninja, and if you're particularly precocious, you might be wondering whether it's possible to access class properties or methods without creating an instance of the class. The answer: yes! The static keyword lets you use a class' property or method without having to create an instance of that class. It works like this: class Person { public static $isAlive = "Yep!" public static function greet() { echo "Hello there!"; } } echo Person::$isAlive; // prints "Yep!" Person::greet(); // prints "Hello there!" When combined with the scope resolution operator, this lets us access class information without having to instantiate anything. Neat, right?

Creating a class:

class ClassName { // Some code } Defining a class method: class ClassName { public function methodName() { // Some code } } Making one class inherit from another: class SubClass extends SuperClass { // Some code } Setting a class constant (remember, no $!): class MyClass { const classConstant; } Using the static keyword: class MyClass { static public $property = "Property"; static public function myMethod() { // Some code } } Using the scope resolution operator: MyClass::$property; MyClass::myMethod();

Do-While?

do { $flip = rand(0,1); $flipCount ++; if ($flip){ echo "<div class=\"coin\">H</div>"; } else { echo "<div class=\"coin\">T</div>"; } } while ($flip); $verb = "were"; $last = "flips"; if ($flipCount == 1) { $verb = "was"; $last = "flip"; } echo "<p>There {$verb} {$flipCount} {$last}!</p>"; ?>

Accessing Associative Arrays When accessing the values from either type of array, the only difference is whether you use an integer, or a specified key:

echo $car[1]; // prints 2012 echo $assocCar['year']; // prints 2012 This exercise will demonstrate how useful specified keys in an array can be.

Calling Your Function

efining our function makes it available for us to use, but we aren't using it until we call it. To call a function, simply type the name of the function followed by any parameters: functionName(parameters);

Introducing 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. An example might be: <?php // get the length of a string and // print it to the screen $length = strlen("david"); print $length; ?>

String Functions strops()

strpos() find the position of the first occurrence of a substring in a string. strpos("emily", "e"); // 0 strpos("emily", "i"); // 2 strpos("emily", "ily"); // 2 strpos("emily", "zxc"); // false The parameters passed to strpos() are the haystack and the needle. The function tries to find the needle in the haystack. It returns either the index of the first character, or false if the needle cannot be found. if (strpos("david","h") === false) { print "Sorry, no 'h' in 'david'"; } // prints the "Sorry" message

Using "Endswitch".

switch ($i) { } But we can also make it this way: use endswitch to replace } don't forget the : switch ($i): endswitch;

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 ( $ ).

• $myName = "Beyonce";


Set pelajaran terkait

Government Unit 3 United States Government

View Set

HA - Chapter 10: Assessing for Violence

View Set

ATI ——— Targeted Med-Surg GI

View Set

FIN 515: Financial Markets & Institutions - Ch. 4 Q&As

View Set