CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
Tutorial - Introduction to Object Oriented Programming
Objects in PHP are an easy way to manipulate a related set of data.
They sort of provide an API (Application Programming Interface) - you don't need to know what's going on behind the scenes, just
what you can do from the front.
Of course, this is if you're using an object rather than programming it. By the end, hopefully this will make some sense.
For this tutorial, we'll start off with some really easy examples and work our way up to a simple shopping trolley.
The code is quite different from other PHP code we've seen - the other PHP code we've done is procedural.
Let's get into it. Here's a class:
<?php
class a // end of function a()
} // end of class a
?>
Well that's a lot of effort to print a simple message. That's a big disadvantage of using objects, they are best suited for large
projects or complicated tasks.
Let's look at it again.
class a
We have to name the class, in this case 'a'. It can be named anything you like with the standard alphabet (a-z, A-Z,
0-9 and _ are all valid). The first character has to be a letter (just like variables), you can't name a class '3'.
Inside the class, we have a set of functions as we've seen before (see the other tutorial on functions if you need a refresher
course
function a
The first function is named the same as the class. This is called the 'constructor', the code inside this function gets
run when you instansiate (or call) the class. You can use this to load data from a database, set up some variables, anything you
can think of. In this case, we're just echo'ing a statement and that's all.
One thing to note is that a class must have at least one function in it, whether it is a constructor or a function of another
name
That's the end of the class. Pretty simple isn't it!
If we saved this file and viewed it in a browser, it won't do anything. We've got the echo statement there, what's going on? We
haven't called the class yet.
Let's add this line to the end - make sure it's not inside the class.
$test = new a();
View the page in the browser now - it will display the text as we'd hope.
We have now 'called' or instanciated the class, this makes it work its magic.
We've created our first class!
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 834
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved