Showing posts with label PHP Guide. Show all posts
Showing posts with label PHP Guide. 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 - Part2 - Getting It On The Screen

OK, so in Part1 we got to grips with basic operators.  But we have nothing to show for blood and sweat.  Let's remidy that.

There are a few ways to get PHP to display to the screen, and while they may apear on the surface to all do pretty much the same thing, they are all different and all there for a reason. In no perticular order here are two of the most common methods:

echo
print

As well as those, there are other commands for more precise displaying of information, but they arn't related to this level of coding. It's as well noting just now that there is a big difference in the way that the PHP processor handles single quotes ( ' ) and double quotes ( " ).  I will ilustrate this difference in the code section for this page.  If you recall, in Part1 there was a line at the end of the code section that started with the following on it:
//EOF...
On the line just above that add the following code using copy and paste, and then save and view the page in your browser, as coverd in Part 0.1