Monday, July 4, 2016

Proin For Dogs


>> doug lloyd: so we'vedone a lot of work in c, and c is a really coollanguage because it gives you the ability to dive reallylow level into your programs. we get to do things asreally minute as manipulating individual bytes of memory.

Proin For Dogs, recall that pointers reallyallow us that flexibility. >> but do we always need to havethat fine-grain level of detail in our programs? probably not, right?

and if we're going to havea trade-off between being able to do really, reallyminute things and really, really big things that we don't have to thinkabout, we don't have to implement these really big ideas ifthey're already built in for us, generally for building bigprograms or big projects, we're probably going to err on the sideof having more language stuff built in for us, instead of havingthe low-level stuff. and that's where php really comes in. >> now, one of the reasonsthat we teach php in cs50

is that it's heavily inspired byc. and in fact, in my opinion, there are really twoprogenitor languages that are very common nowadays. c and lisp. and they're progenitor languagesbecause every other modern programming language that has developedsince then is inspired by one or the other syntactically. php is very similar syntacticallyto c, whereas languages like scheme, for example, whichyou may have heard of,

is heavily inspired by a languagecalled lisp, which is an older language. >> so the reason we teachphp in cs50 is that, by knowing c as fundamentallyas you do at this point, picking up php, which gives you theability to do much higher level things than c does, isn'tthat much of a hurdle, because you already have thebasic idea of the syntax. c's been around for almost45 years at this point. php's been around for about 20 years. and in that 25 yearsin between, programmers

determined that they would muchrather have higher level abilities, and the mistakes and strugglesof the 20 years in between led to php and other modern languages. >> php's a great choice oflanguage for software that allow-- forsoftware that-- where you need to do things that inc are actually complicated. so for example, workingwith strings in c is very complicated, becauseas we know, strings in c are really just arrays of characters.

it's not a built-in data type. or perhaps more fundamentally,something we didn't even cover in c, what if you need to dosome computer networking? all right? >> c has the ability to do it, but it's soarcane and so difficult to actually do. wouldn't it be nice if thelanguage had a built-in, easy way to implement networking? and php is a language that makes that,or facilitates that, quite a bit more. as i said, php is very heavily inspiredby c. the syntax is very similar.

and so it should hopefully make thetransition from one to the other a little bit softer than someother languages might be. >> to start writing php, just open upa file with the .php file extension. technically this isn'tactually required, but if you want things like syntaxhighlighting in ide, so that type names, or variable names, functions,you know, the keywords of the language are highlighted in aspecific color, you generally want to name your files witha particular file extension. so we've named our file with a .phpextension, but then also with php,

all the php code we write in thatfile has to be enclosed in these php delimiters that we seehere on the screen. angle bracket ?php to start. then we write all of our phpcode that we want in between. and then ? angle bracket to close. >> if we don't do this, thenwhat's going to happen? it's not going to crash. it's not going toreally ruin our program.

but it's not going to havethe effect that we want. what's going to happen, really, isthat when we try and run this program, everything not between those delimitersis going to be printed out verbatim. it's not going toactually execute the code, it's going to justprint it out verbatim. >> now why is the case? so c is what's knownas a compiled language. you're probably familiar withthe step of making your programs, turning the .c files and .h filesinto a single executable with make,

in particular usingclang as our compiler. php, though, doesn'thave this equivalent. php is what's called aninterpreted language. and what does that mean? >> well, it means we don't have to convertour source code to zeros and ones beforehand. rather, there's a program,which is also called php, that understands php andcan sort of make it on the fly. that's not really exactly accurate,but it's a pretty good analogy

of what's happening. it's interpreting thosezeroes and ones on the fly. and so if it doesn't knowhow to process something, if it doesn't know how toprocess php, you probably wanted to put that text in there, right? >> you probably wanted to put the code inthere, even if it's not between php-- the php delimiters. but-- so it's not goingto delete it for you, it's just going to basically discard it.

so it's going to printit out to the screen. >> this seems like it's a badthing, but actually it's going to be a reallygood thing, as we'll see when we talk aboutphp web development, because it means we canintersperse php and html. we can use them together tocreate a more dynamic web page. but more on that in thevideo on php web development. >> so what is the syntax of php? that's what this video is all about.

let's talk about it. >> so to start out, variables. php variables exist. there are just two bigdifferences from c. the first is that there'sno type specifier. we don't have to say int,char, float, all that stuff. we don't have to do that anymore. php is a modern language. it can figure out what you'retrying to do or make a best

guess as to what you're trying to do. so that's pretty nice. >> the other thing is that all variablenames have to start with a dollar sign. that's just something to get used to. it's a little weird, becauseit's so that php can understand what's a variable and what's not. so every variable namestarts with a dollar sign. so in c we might say somethinglike this, int x = 54. we don't have to do that anymore in php.

we can just say $x = 54. and we could say, for example, in c,if we had pound-included the cs50 .h header file, we could saystring phrase = "this is cs50." we don't have to do that in php, though. we can just say $phrase= "this is cs50." and in fact, string is nowa built-in data type in php, or rather php understandswhat a string is. it's separate from an arrayof characters like it is in c. all your favoriteconditional statements from c

are still available for you to use. so no big transition there. we can say-- we can haveif statements like this. if $y 43, or $z = 15. so that's pretty straightforward. we can have if and else. we can have if and else if. >> and notice somethingpretty nice here, and this is sort of one of thoseadvantages of php versus c, notice

what function we're not using here? we're using == to compare avariable, $name, to a string. we couldn't do that in c, right? we had to use a function calledstrcomp or strendcomp or any of its related cousins. >> and so already we see these advantages. we don't have to do somethingas silly or perhaps unintuitive as call a function calledstrcomp if i just want to test whether a value equals a string.

i could just use equals equals,like i could do anything else. so there's an advantage. >> sometimes, by the way, you mightsee else if as one word, elseif. and that's ok in php as well. so sometimes you might see that. it's not a typo. php actually understands elseif. i don't know why theydecided to implement that, but as we've seen many timesthroughout our videos so far,

we programmers love it ifwe can do things quickly, so getting rid of that spaceis apparently a big advantage. >> so that's if and elseif. we also have the ternary operator,recall question mark colon, for really short form if elseor conditional branching. and apparently, in this,what we're trying to do here is assign the variable$letter either true or false, depending on whether $varis an alphabetic character. so this is pretty similar to isalphathat we're familiar with from c.

this is sort of the equivalent in php. the function is apparentlycalled ctype_alpha, but that's how we do it in php. so all this is going to be is, if$var is a letter, $letter is true. if $var is not a letter,$letter is false. >> we also have switch statements still. we recall those from c as well. at the very top there, that's how we dosomething like get int or get string. so php has that built in.

we don't need the cs50 library anymore. we can just use the function readline. what that's going to do is printout the message, "your state, please," and then blinking promptwaiting for the user to input some information. now notice what elsewe can do with switch. if you've used it before,you may recall that switch is limited pretty much to integers andcharacters, but now we can use strings. and in fact, the switch statementin php is quite a bit more flexible

than its cousin from c. loops. just like conditionals, all ofyour old favorites are still there. we have while loops that countfrom 1 to 100 in this case. we have do while loopsthat count from 1 to 100, and we have for loopsthat count from 1 to 100. so no big leap there. the syntax is prettymuch exactly the same, except now we're usingdollar sign variable instead

of declaring integer variables orsomething like that for our counters. >> here's where things get alot better than c, though. arrays. so recall when we weretalking about c, in order for us to grow and shrinksets of information, we needed to sort of defaultto this idea of a linked list, because c arrays were fixed in size. we couldn't shrink them. we couldn't grow them.

we had to reallocate memoryand do all this madness or use linked lists, whichtake up quite a bit more space. but in php, arrays arenot fixed in size anymore. they can grow and they can shrink. so again, these 20 years that existedbetween the first release of c and the first release php,we decided that, you know, it would be really greatif we could do this. and so we implemented this. >> so php arrays are not fixed insize, and because php doesn't really

have programmer front-facingnotions of types, we can mix data typesin our arrays, too. so we don't even have to use allintegers or all floating points, we can have a mix of alldifferent kinds in a single array. declaring an array ispretty straightforward. it's just like any other variable. $nums = array (1, 2, 3,4), array being a function that's built into php thatwill create an array for you. this creates an array of four values,numbers in this case, called $nums.

and there's more than one way to do it. and we're going tosee this a lot in php. php has been developed by many differentpeople and grows and grows and grows. there's usually not just two orthree ways to do something in php, there's usually like 10 or 20. here's just another commonway to declare an array. $nums= square bracket 1, 2, 3, 4. so this is sort of similar to c's anglebr-- curly brace notation, rather. $-- or it would be int nums squarebrackets equals curly brace 1, 2, 3, 4.

in php it's $nums = squarebrackets 1, 2, 3, 4. but both of these examples here give mean array of four in this case integers. >> what if i want to tack something on now? well i can just say $nums 4, whichagain, we're still counting from 0 here in php, would be the fifthelement of the array. i can just say that. i'm not going to suffer a segfault, because my array is just going to grow to accommodate that. that's pretty nice, right?

and in fact, i don't even need tospecify where i want to put it. i can just say this and justtack it right on to the end, or i could even justsay $nums 20 or 1,000. it doesn't really matter. it's still just going totack it right on to the end. >> so i can grow, and as-- we'renot going to cover it in here, but i can splice or stripelements out of the array as well, and the array will shrink to accommodatethat now missing or empty space. there's another way to tacksomething onto an array,

which is a function called array_push. so again, just this idea of beingable to do things many different ways. so we've seen three different ways nowto tack another element onto an array. so this adds another elementto the end of the $nums array. and we can mix up our data types. so i could have an array of not1, 2, 3, 4, but 1, true, 3, 4, where true is a boolean, and thenif i want to tack on another element to that array, perhaps a string,the string "five," i could do that. and now my array wouldbe 1, true, 3, 4, five.

the word five, not the integer 5. so a lot of flexibility there. >> the flexibility getseven better, though, because php has support for somethingcalled an associative array. and we sort of vaguely talkedabout associative arrays in c in the context of hash tables, becausewhat associative arrays are really all about are making keyvalue pair mappings. and in this case, the keys-- ifwe're familiar with arrays from c, the keys are index numbers.

0, 1, 2, 3. and the values are what we find thatarray 0, array 1, array 2, and so on. so the keys are indexes,and the values are what is in that array location,specified by that index. >> but in php, we don't have to do thisnotion of array 0, array 1, array 2 anymore. we can now use actual wordsto map keys to values. and so i could say something like this. i could create an array using thesquare bracket syntax as follows.

$pizzas = square bracket"cheese" and then this sort of double arrow notation,8.99, "pepperoni," arrow 10.99-- 9.99, and so on. and so what's going on here? what am i actually doing? i'm creating key value pair mappings. so instead of saying, for example,pizzas 0, pieces 1, pizzas 2, i can now say pizzascheese, pizzas pepperoni, and refer to the valuesassociated with them.

>> so here are our keys in green. cheese, pepperoni,vegetable, buffalo chicken. here is the arrow that makesthis key value pair mapping. and then here are the valuesat that array location. so it's like saying array 0 equals 8.99. the key is 0. the value is 8.99. i can now say array cheese, or in thiscase pizzas cheese, cheese is the key, and what i find atpizzas cheese is 8.99.

that's the value that i find there. >> so i can say things like.$pizza cheese = 7.99. say i'm having a sale. i want dis-- i want to dropthe price of the cheese pizza. or i can use the vegetablepizza as part of a condition, or i can add a new element to myarray, just like i could do previously. i can add a new element to thisassociative array with the key "bacon" and the value 13.49. >> but this sort of introduces a problem,if you think about it for a second.

how would we iterate through this array? right? in c, we would just have afor loop, typically, that would run from 0 to thesize of the array minus 1. the array has n elements in at, thevalid indexes are 0 to n minus 1. so we could use a for loop tostep through every single element. >> but that's not reallythe case anymore, right? now where we have key value pairmappings where the keys are words, how do we iterate over all of the words?

well, fortunately, php hasa way to deal with this too, and so we'll jump backto loops for a second to introduce a fourth kind of loop thatexists in php called a foreach loop. and what a foreach loop does isit's basically the same idea. you can use it for any kind of array. but it's basically thesame idea as a for loop, except instead of usingindex numbers, you just have this weird syntax whereyou call every single element a name for the purposes of this loop.

>> so in this case,foreach($array as $key). basically, as that comment notes,inside of that foreach loop, it's going to go over every singleelement of $array, which is typically going to be an associative array,but can really be any kind of array that you want in php. and every time that ina for loop you might have said $array square brackets$i, you could just say $key. so that $key becomes an alias for everyindex of your php associative array, and so you can use it like that.

>> so for example, we'venow got our pizzas array. i've kind of tucked itinto the corner there so we can use it to do a quick example. if i say foreach($pizzas as$pizza), well, what's happening? well, i'm going to iterate through everysingle element of the array $pizzas, and in so doing, i'm going to callevery element, when i'm inside of the body of that for loop, $pizza. >> so that's sort of astand-in, recall, that $pizza is a stand-in for saying$pizzas square brackets $i

if we were using a for loop, where wecould go from $i = 0 to, in this case, $i = 3. if we didn't have key value pairshere, this would be element 0, 1, 2, 3, and we would use a for loop to go$pizzas 0, $pizzas 1, $pizzas 2, $pizzas 3. so now just $pizza is substitutingfor that individual key. >> so what is this going to print out? i'm printing out $pizza. what am i going to find at--if i print out $pizzas, $i?

if i'm going to print outthe ith element of pizzas, what am i going to print? i'm going to print out thevalues at that location, right? like if we were doingthis in the context of c, we don't usually use our iteratorvariable, int i = 0, i is less than 3, i++, to print out 0, 1, 2, 3. we're printing out array 0,array 1, array 2, array 3. and so what this prints out is this. it's the list of prices.

8.99, 9.99, 10.99, 11.99. >> now a quick note here. a foreach loop does not necessarilyprint out things in order. it's not guaranteed. it usually does. it's usually based on the order inwhich elements are added to the array, so just bear that in mind. it might not be in order. but a foreach loop will iterateacross every single element

of the array in question. in this case, again,that array is $pizzas. >> i can change the syntax, though, ifi want both the key and the value. instead of saying $pizzasas $pizza, i can say this. and if you look at what i'vehighlighted in green here, it looks like a key value pair mapping. and so if you-- even if you are notentirely sure what it's going to do, you can probably guessthat $topping is going to be the key in this case and$price is going to be the value.

so i'm substituting now every elementof $pizzas as a key value pair, and now i can refer to the key andthe value, which might in handy, for example, as follows. >> "a whole"-- this is a lot ofprinting going on here-- "a whole" topping "pizza costs $" price, and theni print out a period and a backslash n. so now, notice again i have access toa key, $topping, and a value, $price. so can you guess what thisis going to print out? there's a lot of print statements,but there's only one backslash n, so it's going to print something onan entire-- on a single line of code.

>> if i can refer to the keyand the value, then now, instead of just being ableto print out the prices, i can print out something like this. "a whole cheese pizza costs $8.99." and now i'm using all of the keys--cheese, pepperoni, vegetable, buffalo chicken-- and the values. 8.99, 9.99, 10.99, 11.99 sothat's just a different way to do a foreach loop that instead ofjust giving you access to the values, it just gives you-- it gives youaccess to the keys and the values.

>> so printing out information. i've already done it a couple ofdifferent ways, you might have noticed. the two functions we've primarilyseen are print and echo. and for pretty much all intents andpurposes, they're exactly the same. they're-- there's a very subtledifference that's not even worth getting into, but basically everywhereyou can use print you can probably use echo as well. >> and that's not the only two. php has a lot of differentways to print things out,

and it also has ways to integratevariables into the middle of string. so recall from c, do youremember what function we can use to substitute variablesinto things we want to print out? you probably use thisfunction quite a lot. printf, right? so this is what we had before insideof the context of our foreach loop. we had these fiveseparate print statements, because that was the onlyway i really knew at the time how to print out messages.

i didn't know how to integrate thevariable $topping into my php code. well, if i just taken a wild guess,printf, it actually would have worked. printf is a function that i can usein php, just like i can use it in c. >> and so something like this, printf,again, we're familiar with that. the first %s is replacedwith the value of $topping. the second %s is replacedwith the value of $price. and so i'm interpellating,which is just a fancy way of saying i'm sticking thevariables into that location. so i'm plugging in $topping where thered %s is and $price where the blue %s

is, and then i would get the message,"a whole cheese pizza costs $8.99." >> not the only way i can do it, though. maybe i would want to use this method. this is actually what's most commonlycalled variable interpellation. i can use an echo. i could use a print too, as we'll see. but what's happening here? >> first of all, i have toescape the dollar sign. because remember, when we were actuallyprinting out the prices of the pizzas,

i was actually formatting them asmonetary figures with a dollar sign. but we're using dollar signs alsoto represent variable names in php, and in particular when i'musing this method of the curly brace variableinterpellation method, i need to escape my dollar sign so it doesn'tthink i'm talking about a variable. it's going to actually,literally print a dollar sign. >> so sort of analogize it towhat you see at the end there. it doesn't actuallyprint backslash n, right? it prints out a new line character.

this is-- it's not going toprint backslash dollar sign, it's going to print out justa dollar sign character. same idea. escape sequences, whatthese things are called. >> but notice that i am not doingany sort of %s substitutions, i'm just literally pluggingin these variables. and so in this-- what would happen hereis that the value of $topping-- again, just keeping with what we've beentalking about so far-- cheese would get plugged in there.

and $price would be whatever value isat pizzas, square brackets, cheese, which was 8.99. and so this would also print out"a whole cheese pizza costs $8.99." and like i said, i could useprint here instead of echo, and the functionality bepretty much exactly the same. it would print out the same thing. >> there's another way to do it,and this is another advantage of php working with strings. we can do string concatenation.

we could do this in c, too,using a function called strcat, but again, we had tocall separate functions. it was this whole mess to do. we had to pound-include string.h. it was a production, right? but now i can just use this dot operatorto concatenate strings together. >> so i'm concatenating "a whole" andthen whatever the value of $topping is, and then anotherstring, " pizza costs $" and then concatenating whateverthe value of $price is,

and then at the very end i'mtacking on period backslash n. and so this would alsoprint out "a whole"-- again, if we're talking about the firstelement of that pizzas array-- period, backslash n, again, withthe $topping and $price substituting for what we had specified in our foreachloop as the key value pair mapping. >> php can handle functions. functions were sort ofintegral to c, as we saw. like variables, we don't need tospecify the return type of the function, because it doesn't really matter.

and we don't specify thedata types of any parameters, because they don't reallymatter, like we've seen in php. every function is introducedwith the function keyword. that's how we indicate to php thatwhat we're talking about is a function. >> and we don't have todeal with main at all, because the interpreter, the phpinterpreter, works from top to bottom, regardless. if it sees you can makea function call, it'll go find the function call,even if it comes later.

but it's going to read from top tobottom, so we don't need to specify, here's where you start. you start on line 1 of yourphp and work down from there. >> so here is how we would createa function called hard_square. it apparently takes oneparameter, which i'm calling $x. this function is complicated justto illustrate various things. we still have return values. i'm using a for loop here. but it's basically just, what thisamounts to is just $x times $x.

what i'm actually doing is just addingx to 0 x times or $x to zero $x times. but it's effectively exactly thesame as multiplying $x times $x. i can still return a value,in this case $result, and i've made a function in php. >> here's how you might use it in context. so maybe i'm inside of some php file. notice in blue there thati've used my php delimiters, angle bracket question mark php. in between those are all ofthe php that i want to write.

so i'm apparently going to get--i'm going to prompt the user to give me a number, store thatvariable, store in that variable $x, whatever they gave me. then i'm going to echohard_square of that value, and apparently goingto tack on a new line as well, and then later on i'lldefine the function hard_square so that when i make thecall to hard_square, it knows what i'm talking about. >> now, i could also dosomething like this.

this is slightly different. it's almost exactly thesame as what we saw before, except instead of saying just $xthere as the parameter to hard_square, i'm saying $x = 10. so this is an example ofdefensive programming, guarding your programsagainst malicious users. >> this is one way to do some errorchecking that we didn't really have as an option in c. we could neverspecify the default value of something. we always had to checkwhether the, for example,

if we made a call to getstring, it wasmost proper if immediately after we checked that, we checkedwhether the string that the user gave usis not equal to null, because we don't want to startworking with a null string. >> here, this is a wayto guard against that. if the user doesn't provide us somethingsomehow, what are we going to do? well, we'll just say whateverthey didn't provide us, we're just going to plug in 10 instead. so if they didn't give us a value,just use 10 by default. and so here,

notice that i'm makinga call to hard_square, but there's no promptto the user, right? i'm just making an empty call. >> but my function hard_squareis expecting a parameter. what is this going to print out? it's going to print out 100, right? because the user didn'tgive me anything. and so i'm just going to assumethat 10-- 10 is the default value. and so this would printout 100 on its own line.

>> php files do not have tobe just a single file. you can combine multiple files together,just like you can in c. the way we did that in c was typically to do a#include to get header files pulled in. we don't do that in php. we do something called require_once. and then there's this wholething, what's this __dir__? that's just a specialvariable, or special constant, really, that specifies whatyour current directory is. and so it's going to lookin your current directory

for a file called cs50.phpin this example here, and it's going to stick that fileat the top of your php program, assuming that you put the requireonce line at the top of your php file. >> so php is primarily used,but not exclusively used, as a language for web-based programming. that's really how it came to be. but it is a fulllanguage, as we've seen. we've seen pretty much all the thingsthat it can do that are similar to c, and it can do a heck ofa lot more than that.

>> but because it's a full language and wecan do command line programming in it. we can run command line programs. all that's required to run a commandline program that's written in php is that you have a php interpreter. so it's sort of analogous tohaving a compiler on your system if you want to compile your c codeto turn it into executable files. you need to have a php interpreterthat exists on your system so that you can interpret php files. >> assuming you do, and usuallythis interpreter is called php,

and it's usually bundled with mostdownloads or installations of php that you can get online, and certainlythe name of the php interpreter we have in cs50, ide. all you do is type php file. and what your program'sgoing to do is it's going to run throughthe interpreter, it's going to ignore everything that'snot in between question mark-- or, angle bracket question mark php,the php delimiters, and print it out, and it will interpret and execute thecode inside of your php delimiters.

>> so let's pop over to cs50 ide andhave a look at a couple of php files, running a couple of php files, incommand line interface of cs50 ide. so here we are in cs50 ide,and i've taken the liberty of opening a file called hello1.php. and apparently, the contents of thisfile are just the php delimiters there, and in between, echo("hello, world"). this is a pretty simple php program. i'm just going to scroll downto my terminal window here, and i'm going to type phphello1.php, hit enter.

hello, world. that's probably what we wereexpecting it to do, right? >> let's go up and takeanother look at a program. hello2.php. pretty much the same thing,not a lot going on here. this time, though, i'm going to promptthe user to give me their names. i'm using that readline function again. $name = readline. that's the prompt, "what is your name?"

>> apparently i'm printingit on its own line. and then, so the line belowthat will be the prompt where the user can enter their name. and then i'm using a little bit ofvariable interpellation here on line 3 to print out "hello" andwhatever the user types. so this is analogous to saying, hello,comma, %s if we were using printf in c. >> so let's go and interpret this program. so again, i'll scroll downto my terminal window. php hello2.php.

what is your name? doug. hello, doug. i also have anotherfile called hello3.php. i'm going to clear myscreen with control l, and i'm going to execute that. so the behavior is identical tohello2.php, but why is it hello3.php? >> well, here's the difference. in this case, noticethat on line 1 here,

i have something that's notin between the php delimiters. i'm just printing out-- or ijust typed, "what is your name?" when the php interpreter sees this, ithas no idea how to interpret it as php, and so instead of failing,it's just going to spit it out. >> so notice on line 3 now, my call toreadline, there's no prompt anymore. i'm just actually going to-- whenthe php interpreter sees this, it's going to print out"what is your name?" then it sees, oh, ok, here's--everything else is going to be interpreted as php, sothat's why this works.

i don't have to necessarily promptthe user to-- inside of readline, i can just have it outsideof the php delimiters and allow the interpreterto just print it out for me. >> so you don't actually only haveto have one set of php delimiters in your program. you can actually have several of them,opening and closing them as needed. so let's take a lookat a couple of programs in cs50 ide where weillustrate this idea of having multiple sets of delimited php.

>> ok, so i've opened a filehere called add1.php. and notice what's happening here. just as before, i have asingle php set of delimiters. i'm going to print out themessage, "please give me a number." then i'm going to read a line andstore it in the variable $num1. then i'm going to print out again. give me a second number. read a line from the user, storewhatever they typed in in $num2. add them together and store thatresult in a variable called $sum,

and then print out, "thesum of these two numbers is," and then interpellatethere the variable $sum. so let's just run thisthrough the interpreter to confirm that this is what we expect. php add1.php. please give me a number, 3. please give me a second number, 4. the sum of these two numbers is 7. that's 3 plus 4.

ok? so nothing terribly fancy there. >> and now let's open up add2.php. here, i've got a couple of phpdelimited sets there, right? lines 1, 3-- lines 1 and3 have no php delimiters. so when the interpretersees them, it's just going to spit out exactlywhat i have typed there. so that's where i'mdoing all my prompting. on lines 2 and 4, we see the veryfamiliar $?php sort of delimiters,

so those two lines aregoing to execute as php. and then on line 5, i have thisweird thing right here, right? this angle bracketquestion mark equal sign. i'll even zoom in a little bit further. you can see this is what i'mtalking about right there, this $?=. >> it turns out that it's so common thatthe reason that we open up a set of php delimiters is to print out a value. and that's all we're going to do. but there's even shorthand for that.

$?= is php shorthand for sayingsomething like $?php echo the sum of num1 and num2. so this is just anothershorthand for that. >> so if i run this program, php add2.php. i'll zoom down a little bit. please give me a number, 4. please give me a second number. and since i don't really care aboutdata types in php, i can say 4.8. the sum of these two numbers is 8.8.

that function behaves pretty muchexactly the same as we would expect, as well. and i have one more openedup here called dice.php. try this again. i have one more here calleddice1.php, which also, see, has that angle bracket questionmark equal sign notation in there, but notice that in this case i'mcalling the function rand, which as you might expect generates a random number. "you rolled a," and it's going tocalculate some random number, mod 6 +

1. so that'll give me numberin the range of 1 to 6. >> remember that mod 6 would give mea number in the range of 0 to 5, but if i'm simulating dice rolls,which is what i'm doing here, i don't want these dice to go from 0to 5, i want dice that go from 1 to 6. and so this is a way to getme in the range of 1 to 6. i'm doing this twice. so apparently i am rollingtwo dice in this program. >> so i'll clear my screen,and i'll do php dice1.php.

you rolled a 4 and a 2. and if i run the programagain, you rolled a 5 and a 5. so every time i run the program,i'm getting different numbers, because every time i doso, it's starting over. it's going to generate a newset of random numbers for me. >> so if we're used torunning programs from c, we're used to typing ./ thename of a program, right? that's how we've done allof our programs in c so far. we can do this in php as wellby adding something called

a shebang to the top of our php file. i know it's kind of a silly word. it's short for hash bang. that's the first two characters there. remember we call exclamation pointfrequently a bang in computer science. it also might be for sharp bang. there's a couple ways to interpret it. but it's basically a special sortof command that the php interpreter understands as, oh, i wantyou to execute this program,

which is apparently /user/bin/php, whichis actually where the php interpreter specifically lives on our system. so it's-- what happens here isthe interpreter understands, oh, i'm apparently supposed to usein this program to run this file. and so it allows youto skip over the step of having to say php something.php. there's one other catchhere, which is that if we want our programs towork as expected, we need to do something calleda file permission change.

and we'll go-- and we talk a littlebit more about file permission changes in our video on mvc, but suffice it tosay that this is what you need to do in order to make your.php files executable. so let's take a look at this asour final example over in cs50 ide. >> so here in ide i have two files in thisphp directory that appear not to be called .php. i have a function called add--i have a file called add3 and a file called dice2. so let's take a quicklook and open up add3.

and as you can see, at the beginningof my file i have this shebang, right? this hash mark exclamation point. now, you'll also maybenotice that for some reason, i don't have any syntaxhighlighting anymore, and this is what i alluded to earlier,which was that if i don't name my file .php, i don't have the benefitof syntax highlighting anymore. this file is just called add3. so that i can run it later onwith ./ add3 and not ./ add3.php. >> so the reason-- it's stillfine, it's still valid php,

but it's not syntax highlighted, becausethis file is not called something.php. that's the only real differencehere, plus the shebang. so let's see what happens wheni try and run this program. ./ add3, just like i would with c. bash. ./ add3 permission denied. this is what you're goingto see if you forget to use the chmod command to changethe permissions of the file. >> as it turns out, regular phpfiles cannot just be executed. they can be interpreted, but we'redoing something a little different here.

we're executing it. and so i need to add the permissionof execution, chmod a+x to add3. then i can say ./ add3. please give me a number. 5, 6. the sum of these two numbers is 11. >> similarly, i have already chmodeddice2, so i can just type ./ dice2, you rolled a 1 and a 1, yourolled a 5 and a 4, and so on. >> so that's pretty much theidea of a php syntax, right?

there's a lot to get through, i know. but hopefully you've seen now that phpis not really that different from c and really gives us the abilityto take things up a notch or two. we don't really have to worrytoo much about-- we don't really have to worry too much aboutthe low-level details we had to worry about with c, right? we can focus on the higherlevel stuff that php allows us to do and to take forgranted that it will work for us.

Proin For Dogs

so it gives us the ability now,transitioning from c to php,

to make programs that are a lot morecomplex and perhaps a lot more robust. >> so i hope you have fun workingwith php, and i'm doug lloyd. this is cs50.

No comments:

Post a Comment