Showing posts with label PHP for begginers. Show all posts
Showing posts with label PHP for begginers. Show all posts

Thursday, 1 November 2012

PHP Classes - A Simple Sample Class

PHP Classes - A Simple Sample Class


OK, so in the last two posts we covered the basic theory of objects. Now lets go ahead and make one.

To create an object in PHP we use the term "class" in the same way we would use "function". 
So what can we make an object for? Well pretty much anything really.  To keep it simple at the start we'll go through making an object that simply manipulates some text.

So lets make our object, I'm going to be calling it "myText"

<?php
class myText{

}
?>

There, that was easy enough.  Note that unlike functions there are no parenthesis after the name of the class that you can pass variables into.  We'll come back to that later on.  Now we'll add the first method.  The first thing we are going to need to do is get the text that we will be formatting, so lets create a method that will do that, this one I'll be calling "getText".

<?php
class myText{

 public function getText($textIn){
 
 }
}
?>

Hmmm....hang on, what are we going to be doing with this text after we get it?  Well the idea is that we can search the text for occurences of the word that we choose once it's loaded into the object.  So any method could need to access the text.  Guess we had better stick in an object level variable - these are actualy called paramters, but for now I'm going to keep calling them variables -  to keep the text in so that all the other methods will have access to it and then have the getText method send the text it gets out to this variable.

<?php
class myText{
 public $text;

 public function getText($textIn){
  $this->text = $textIn;
 }
}
?>

OK, so that's that done.  See the use of $this->text ? when working anywhere inside a class $this is basically a short way of saying "This Class" or "This Object".  the use of -> is saying which variable or method within the class or object to are referring to.  Also note that the $ is dropped from any variables that come after the -> (but you still need to use the parenthesis at the end of function names). So $this->text=$textIn tells the method that it is going to take the contents of the $textIn variable and send them to class variable $text.  You will also have by now (I hope) noticed the word public at the start of both the $text variable and the getText() function.  These are here to explicitly define the scope of each of these.

Right, so we have a method of getting text into the object now.  Let us now make a method that will do something to that text.

<?php
class myFormat(){
 public $text;

 public function getText($textIn){
  $this->text = $textIn;
 }

 public function makeCaps(){
  $this->text = strtoupper($this->text);
 }
}
?>

So now we have a method that will make all the text uppercase. Not exactly anything to write home about, but it at least lets us see how easy it is to address variables that are stored at the object level from within a method.

Let's blast on and add a couple more methods to play about with the text, we'll take a look at them once we're done adding them all.

<?php
class myText{
public $text;

  public function getText($textIn){
    $this->text = $textIn;
  }
 
  public function makeCaps(){
    $this->text = strtoupper($this->text);
  }
 
  public function delimit(){
    $delimitText = $this->text;
    $delimitText = str_replace(".", "", $delimitText);
    $delimitText = str_replace(",", "", $delimitText);
    $delimitText = str_replace("\n", '|', $delimitText);
    $delimitText = str_replace(' ', ',', $delimitText);
    return $delimitText;
  }
 
  public function txtToArray(){
    $txtForArray = $this->delimit();
    $textArray = explode('|', $txtForArray);
    for($i=0; $i<=count($textArray)-1; $i++){
      $textValue = $textArray[$i];
      $textBack = explode(',', $textValue);
      $textArray[$i] = array_filter($textBack);
    }
    return $textArray;
  }
 
  public function findWord($word){
    $haystack = $this->txtToArray();
    for($i=0; $i<=count($haystack)-1; $i++){
      $result = array_search($word, $haystack[$i]);
      if($result != false){
        $line = $i+1;
        $wordNo = $result+1;
        $return[] = "Line No $line, Word No $wordNo";
      }
    }
    return $return;
  }
}?>

OK, so that's a whole bunch of code that you may or may not fully understand.  Suffice it to say we have just added some methods that take in a text string, strips all full stops and commas out of it, splits the text ito lines (using the linux/unix \n control character, if you want to work with windows controls change the str_replace("\n"... to str_replace("\n\r"... ) and words and then lets someone find a word in the text returning each location by line and then number of words along that line that the number is in.  Look over the delimit() and txtToArray() methods and you will see that they are very similar to the normal functions you would write outside of a class/object.  they take in values and return other values and you can even call one method from inside another.

So now that we have made our class it would be good to get some output from it.  Lets drop down outside the closing } of the class and add the code to make the class do something.

...
}
$mySearch = new myText();
$mySearch -> getText("This is some sample Text\nUsed to test out our sample class.");
$searchResults = $mySearch->findWord("sample");
if(count($searchResults) >= 1){
echo "word \"sample\" found at the following locations:<br>";
}
foreach($searchResults as $result){
echo "$result <br>";
}
echo"<br>Within : <br>{$mySearch->text}";

?>

Notice that there is still the parenthesis when you call a new class, even though we didn't use any to declare the class at the beginning? Remember how I said we would come back to that? well here we go.

Classes have special methods, one of the most important is the constructor.  This lets the class gather everything it needs when it is created.  Lets modify our class a little bit and add the following constructor method at the top :

<?php
class myText{
public $text;

  public function __construct($text){
    $this->getText($text);
  }

  public function getText($textIn){
....

OK, now we have a constructor in place, what this does is load the text into the object as it's created.  This makes sense in the example here because the object depends on having sent into it for it to really do anything. now when we create the new object we add the text into the parenthesis there, and skip the line that calls the getText method altogether.

...
}
$mySearch = new myText("This is some sample Text\nUsed to test out our sample class.");
$searchResults = $mySearch->findWord("sample");
if(count($searchResults) >= 1){
echo "word \"sample\" found at the following locations:<br>";
}
foreach($searchResults as $result){
echo "$result <br>";
}
echo"<br>Within : <br>{$mySearch->text}";

?>

That's almost it for our first look at classes, just one more thing, the scope.  So far we have made everything public, this is the best way to create a new object because it lets you access each of the methods and variables for debugging.  Now we have finished it, we can change some of the scope.  For methods and variables that you don't want anything outside the object to access you can set it to either protected or private.  Private goes a step further and stops child objects and/or parent objects accessing the method/variable either.  Again it's not something we'll be getting into here, but for the sake of an example, change the word public that is before the $text at the top of the class to protected and see what happens when you run the code again.
Not good, huh? It stops the code getting direct access to the variable inside the object, so lets change that back.  Where protected would come in handy would be to use it for the delimit() and txtToArray() methods, this would stop anyone calling these methods directly and potentially using them out of context.

Anyways, that's it for this "beginner class" (pun intended).  I suggest that, assuming I didn't confuse you too much, you look into patterns in PHP. These are guides to standard designs for creating your own objects.

Tuesday, 30 October 2012

PHP Classes - What is an Object?

So What Is An Object?

This isn't an easy a question to answer, and I am sure by the time I am done I will have you wishing you never asked, but you did so here it is, and as I have just renewed my membership to the "Analogies Fan Club" I'm going to make use of a rather drawn out analogy to help me with this.
For this analogy I am going to assume that you live in a house, know someone that lives in a house, or have at least had a walk about inside a house.  As I hope you will all agree, a house is an object (in the physical world at least).  Well lets take that and make it an object in the programming sense.  A house has one or more rooms.  These rooms, when transconceptionalized (yes, I just made that up) into the programming sense become methods.  So taking a general 2 bedroom house with lounge, kitchen and bathroom gives us an object called house with methods called lounge(), kitchen(), bathroom(), bedroom1(), and bedroom2().

Right, so that was easy enough.  Now to deal a little bit with "Scope". Scope is the term used to describe how visible a method or a variable is.  You can have variables within the root of the object as well as within each of the methods.  And just like rooms in a house variables of the same name that are in different rooms are kept apart from each other. so if you have a variable called TV in lounge() and a variable called TV in bedroom1() anyone who comes to the house to watch TV can be sent to either of these rooms either by you or by knowing when they arrive, if you made the TV variables public, which room is showing the show that they want to see.  So that's variables within the methods touched on, now for the variables in the root of the object.  These variables are generally used to describe the object, or to hold the information withn the object that isn't specific to the methods.  So a house could have variables that state the people who live there, the amount of electricity gas and water the house uses, phone line information, how many times there has been a delivery to the house by a courier and what the courier company was.  These do not need to include variables for things within methods that can or often do pass into other methods.  So for example you do not need to have an object level variable called "$dadsCoffeeCupLocation" to track the movements of said sacred artefact around the methods of the house. each method can relate directly to any other method within the object and pass information that way.  What's more, a method can also be an activity that goes on in the house, as well as the room in which it happens.  So you could have a tracking method that is dedicated to the task of keeping track of "$dadsCoffeeCup" as it is passed between each room method.

So, starting to sound more than slightly complicated?  Believe it or not, it's actually a good thing if it is.  Objects are simple on the outside and complicated on the inside.  This means that, once you have coded the complex stuff once at the start, it's really dead simple to access the stuff that the object contains. 

PHP Classes - What is OOP?

What is OOP?


So, OOP. What is it and why is it so good? OOP, or Object Oriented Programming, is the term given to programing languages that either let you, or insist that you, program the code using general objects to create the processes that the program will perform.

Not too helpful huh?  OK, lets take a step back for a moment.

Some History

In the beginning (well not the beginning, as in 1843 Ada Lovelace beginning, more kind of late 1950's - 1960's type beginning) there was Assembly Code (there actually still is assembly code, it's just that these days it's something of a social recluse). Assembly Code is about as close as telling the computer exactly what to do as someone with higher language skills would ever want to get.  This language had no procedures, no functions (per say), no classes and no modules.  This meant that as the number of programmes working on any given project increased - so did the complexity of keeping the overall code intact.  As each programmer worked on a specific piece of code that had to interact flawlessly with every other piece of code.
As far as Assembly Code went that was manageable, because the language is low level, the commands that the language accept are pretty limited.  However, people got to thinking "there has to be a better way to do that", and (thankfully for the rest of us) they were indeed right.  Other Languages started being developed that were designed to act as a translator between the way the brain works and the assembly code used to make the program work.  And so the evolution of programming languages had truly begun (it was actually begun in the 1940's, during the second world war, by a very clever German gent called Konrad Zuse, but that's a different level of evolution).
So as things progressed languages got more and more "human friendly".  Part of this happening was alterations to how people programed.  The big step was the arrival of Procedural Programming.  This allowed programmers to write complex subroutines once within the program and call them for re-use as and when needed.  It also meant that a group of programmes could write independent procedures for the same program and  these procedures could be incorporated into the overall program in a much more modular way, allowing for much smoother integration of code into the overall program.  Procedural programming was great.  At the time. Now its been relegated to the standing of only "Damn Good" and title of Great has been taken by the Object Oriented kid from three doors down.

Now To The Point

Object Oriented programming took Procedural programming and pimped it up.  Procedures became known as Methods within the objects known as Classes.  Instead of having a whole list of procedures loaded at the start of the program now you can have a whole bunch of objects that are only loaded when they are used by the program.  These objects can also be stored in a library and are generally easier to organise than the Dewey Decimal System.

So What's This To Do With PHP Then?

Well PHP is an object oriented language.  However, it's not strictly an object oriented language.  What that means that one of the things that makes PHP so much fun to use and what makes PHP so easy to pick up, is that it is what's called a "loose language".  This means that it isn't strict about how you program in it, as long as PHP can make sense of the logical steps you have used to write the program then you will get away with it.  Other languages aren't quite so relaxed about how you code - Java by SUN/Oracle for example will have no hesitation in throwing the toys not only out the pram, but squarely at your face if you try and code without using objects.  Yes choice is good, but then again, so are rules.  PHP's loose nature can, and very often does, cut both ways.





Friday, 11 May 2012

PHP - Where To Start - Part 0.1 - Genesis

In The Beginning there was only darkness...Then the power came on and someone thought it would be cool to have a scripting language that ran on the server side but was still processed from within the web server it's self, without needing to run off and buy some application resources from a service down the street that it didn't really get on with in the first place.

PHP is that scripting language.  It stands for (rather puzzlingly) Hypertext PreProcessor, however it was originally coined as (somewhat more understandably) Personal Home Page. The guy that had the thought that it would be cool also had the thought that it would be way better if it was free for people like you and me to play around with (just like your mum's cleaning products were when you were playing at making explosives). His name was Rasmus Lerdorf and he single handedly wrote the first two versions of PHP.

And so we have PHP, accessible to all.  Whole communities have even been built around it's humble foundations.  It's impact on the web is immeasurable. And now were going to cover the basics.

This is an analogous description of the fundamental information about PHP.  It's not meant to be taken as a gospel truth, but rather its meant to help get some key concepts to stick so you can get on with the fun stuff.  

PHP is, as I said in that nonsense at the start, a scripting language.  This means that it does not require a compiler to run, it just shoots down each line of the code as if running the hurdles.  It's very lite, and apart from the PHP software it's self, and a web server software, you don't need any special toys to make it come out to play.

If you are running windows, the best way to get from nothing to a working php setup is (in my all devouring opinion) to go download XAMPP from www.apachefriends.org and install it.  I suggest installing it to c:\xampp, but where you put it is your call, just know that you are going to want to get into that folder a lot. One important thing I will say is not to use ANY spacial characters in the path name, so no ~'s or #'s or anything like that. This isn't an issue for the PHP side of things, it is however a huge problem if you every want to use the PEAR application.

Once you have a working environment you will need something to make your php pages with.  This bit's as easy or as hard as you want to make it.  You can simply use notepad (NOT wordpad - notepad, they are different) but this will give you no visual aid when coding.  You can download for free a coding specific text editor like pspad, notepad++ or any number of other alternatives.  You can download, again for free, the eclipse IDE for java and then download the PHP Language add on.  Or you can spend some money and buy an IDE such as Dreamweaver or Zend Studio Pro (I actually do not recommend the use of an IDE for someone who is just beginning, they have a lot more in them - especially Zend Studio - than you will use at this level, and the extras make getting confused a lot easier).

After you have settled on your application you're almost ready to get on and make your first php page.  Open up your program and choose new file (as I have no idea what program your likely to be using your going to have to work out this complication on your own).  You want to then go immediately to Save As... and navigate to where your web root is.  If your using XAMPP that will be in the directory that you installed XAMPP to and then into the directory called "htdocs".  Once there save the page as "index.php" making sure that, if the program supports it, you have selected the extension type as php and if the program doesn't support php file extensions you select "all files" as the file type.

Now you have, in effect, created your first php page.  How'd that feel? crap? really? Yeah I get where your coming from, but let's be fair, if I told you to put the 3 lines of code in the file that would have had show "hello world" you wouldn't have felt any better about it, would you? especially as I haven't gone over how to actually view the fruits of your coding loins.

First we need to make sure that the web server is running, so in XAMPP (if your not using XAMPP I'm gonna assume you went that road because you know what your doing, and I'll will leave you do your thang) You want to launch the XAMPP Control Panel, either from the start menu, or from the desktop shortcut (sometimes on Windows 7 you will get a message about this thing must be run from someplace that your sure is where it was just run from, you can normally just ignore that and click whatever button it presents you with).  In the control panel have a look at the list under Modules, the top option should be Apache.  If this has a green "Running" beside it, your all good, if not click the "Start" button and watch the white box.  you should have the Running message displayed in a few moments.  OK, so now were running a web server.  This is important, because your PHP pages need to viewed through the web server to be processed. So if you want to view your PHP page, it's pointless going to C:\xampp\htdocs\index.php because that's just going to show you the raw code. What you need to do (This Is VERY Important!) is open up your Internet browser and then find the address bar.  In there change the content to be http://localhost/index.php and there you can see your page.  It's blank just now, but as we move through sections we'll get to that.

One final, impossible to progress without knowing, thing before we drop into the coding of our very own super-fantastic PHP pages, EVERY PHP Page MUST have
<?php
at the start and
?> 
at the end. This is what tells the web server "process my damn code fool" and without them, everything will go horribly horribly wrong.

Right, on to Part 1 then...