Jump to content

php classes


Recommended Posts

A class is a blueprint for an object. You can use the same blueprint (class) to create multiple objects. The class will define what properties are used to describe the object(s) and define what methods are used to interact with the object(s).Assume you create a class for cars, the properties may be the 'engine_size', 'color', 'make', and 'year' of the car. Methods may calculate the MPG based on the 'engine_size' property.Objects are self-contained black boxes, making them easy to use -- you don't have to know the inner workings of the class to use them.WG

Link to comment
Share on other sites

Well, classes do allow objects to be created, don't they? :) And those objects are handled very much the same as in JavaScript, exept at least the property is delimited by another sign. So classes are used to be able to create objects like in JavaScipt, am I right? I not yet have fully read the documentation though :)What is the difference of using an object, what is the advantage, over using just arrays? Could you persuade me using classes :)

Link to comment
Share on other sites

Umm, can someone please explain classes without using real world objects, that's why I never understand, I need to understand how classes work when talking about php, even the php book I have " in a nutshell" or something uses dog and cat, I can't sit down with a php script and tell a dog to bark, and a cat to meow, I need to know where I will use this, any examples appreciated.

Link to comment
Share on other sites

You may have heard of "object-oriented" programming (OOP). Classes and objects are at the center of OOP, along with concepts like inheritance. Other types of programming languages other than OOP (they call the types 'paradigms') include functional and imperative, in addition to many others. There is a wikipedia entry on paradigms here:http://en.wikipedia.org/wiki/Programming_paradigmParadigms are sort of like the way the programming language works, or is structured. Before PHP 5, PHP, like C, was an imperative language, but PHP 5 added true classes and objects, so these days you can write PHP in an imperative or an object-oriented style, or even mix them in the same program. Many of the references on php.net have examples for both ways.But an example of OOP without using real-world objects is pretty difficult, almost everything you represent in programming is a real-world object. I guess a good example would be a user, every system has users. So say you want to keep track of your users, you want to track their user name, login time, age, location, whatever. If you wanted to take a non-object-oriented approach, you could probably set up an array or use function calls to do this. PHP has full support for associative arrays, meaning that you can use strings for the array keys instead of numbers. So instead of having this:$users[0]$users[1]You can have $users['steve']$users['dan']etc. Earlier languages like C did not support that, you referenced array elements by a numeric index only. So, associative arrays are much like objects for storing only variables, or properties. But it becomes a little more cumbersome if you also want to store functions, or methods. In object-oriented speak, objects do not have variables and functions, they have properties and methods. But they mean the same thing, properties are variables inside an object and methods are functions inside an object. The point is to group them all together so that you can re-use, make other objects that inherit properties and methods from parent objects, and things like that. So if you want to create a user object, you might have something that looks like this:

class User{  var $name;  var $last_login;  var $age;  var $location;}

Here you are just creating one object that has all the different properties in it. So you would use that like this:

$user = new User();$user->name = "login name";$user->last_login = time();

etc. But this is only half of objects, the other half is methods. So you can add a few methods to your object to help automate things:

class User{  var $name;  var $last_login;  var $age;  var $location;  function set_name($str)  {    $this->name = $str;  }  function get_name()  {    return $this->name;  }}

The $this variable inside an object always refers to that instance of the object, it refers to itself. So, even though those methods are only 1 line each and are really simple, you can probably see that you can use methods to add functionality to your objects. A special method is the constructor, which gets called every time you create a new object and uses the same name as the class. So since the class is called User, the constructer will also be called User. Since constructors get invoked whenever a class gets instantiated or created, then you can put your initialization code in there:

class User{  var $name;  var $last_login;  var $age;  var $location;  function User()  {    $this->last_login = time();  }    function set_name($str)  {    $this->name = $str;  }  function get_name()  {    return $this->name;  }}

One of the main benefits of objects is the fact that you can create objects based off of other objects, that inherit all of the properties and methods of the parent object. If you already have a User object, and you want to create an Administrator object with additional properties and methods, you can just have the admin object inherit or extend the user object, and that way you don't have to recreate everything you did for the user object. You can also create a serializable object, which means that you can write the object to a file, database, or session, and then read it back in and unserialize it to get all of the information that was in it when you saved it. There are a lot of benefits to using objects, but it really comes down to your preference. But some programs will benefit a lot from making use of objects, programs can be faster, smaller, and more maintanable with object then without. But it's all about being able to identify where objects make sense to use. For example, I created a template engine for myself, and the heart of a template system is the page itself. So I created a page class, with support for loading in things to replace, methods for parsing the template and actually doing the replacements, etc. Which makes it really easy to setup and display a page:

  $page_name = "Login";  require_once("include/template.php");  $page = new Page();  $content = array();  $content['sys_name'] = $SYSTEM_NAME;  $content['sys_path'] = $HTTP_SYSTEM_PATH;  $content['page_title'] = $SYSTEM_NAME . ($page_name != "" ? ": $page_name" : "");  $content['error_text'] = parse_errors();  if (isset($login_id))    $content['login_id'] = $login_id;  if (isset($setcookie))    $content['setcookie'] = $setcookie;  else    $content['setcookie'] = "true";  $page->set_template("login.wtf");  $page->process($content);  $page->output();

That's all the code that is required to display my login page. All of the HTML is actually in a template waiting to get replaced by the values that I give my page object, and above that code is the code that gets executed when someone actually logs in. But to display the page itself, instead of a legion of echo statements or embedded HTML, that's all I need to do.So, classes simplify a lot of things, but only if you use them correctly. I can't really convice you in this amount of time to use or not to use objects, but if you are interested then you should do a little reading into OOP and why people use it. Java, for example, is entirely object-oriented, and that is also one of the major differences between C and C++, so there is a lot of support for it and a lot of people using it. .NET is also OOP. If you want a discussion on object orientation in PHP, look here, there is a discussion both for PHP 4 and PHP 5:http://www.php.net/manual/en/language.oop.phphttp://en.wikipedia.org/wiki/Object-oriented_programming

Link to comment
Share on other sites

It depends on the situation, both objects and arrays have their place. If there was an obvious answer that one was better than the other, people would be using that one and there wouldn't be a question. But arrays and objects are different structures for different purposes, and both have their place.

Link to comment
Share on other sites

I understand :)And I will check up on some things and test them to find out for myself what is best to use :) If I can't find it, I'll ask here. But php.net is also a great resource, so I can search there to for facts.

Link to comment
Share on other sites

Well, classes do allow objects to be created, don't they? :) And those objects are handled very much the same as in JavaScript, exept at least the property is delimited by another sign. So classes are used to be able to create objects like in JavaScipt, am I right? I not yet have fully read the documentation though :)What is the difference of using an object, what is the advantage, over using just arrays? Could you persuade me using classes :)

No I will not try and persuade you to use them. They make reusing code a breeze. And when I said it wasn't like objects in javascript I meant the syntax is completely different and that php classes are more complex then objects in javascript.
Link to comment
Share on other sites

is there a PHP equivalent of Javascript Object()?

The Javascript Object() function just returns a new, empty object that you can use to store properties and methods. Typically, you probably shouldn't be creating dynamic objects, chances are you know what properties and methods it should contain. Therefore, you should create a class in PHP with the properties and methods in it and use it to create whatever you need.If you want to give an example of something in Javascript that uses an object, I will try to show you how to do something similar in PHP.
Link to comment
Share on other sites

I like PHP objects, you can create multiple instances. Especially the methods is a feature I like.

<html><head><style type="text/css">body{font-family: verdana}a, a:visited{color:#00f}a:hover{background-color:#408}</style></head><body><?phpclass WWWLanguage{	var $name;	var $link;	var $description;	function WWWLanguage($name, $link, $description)	{  $this->name = $name;  $this->link = $link;  $this->description = $description;	}	function displayLanguage()	{  print("<p><a href=\"http:\\\\www.w3schools.com\\$this->link\" target\"_blank\">$this->name</a><br />\n");  print("$this->description</p>\n");	}}$html = new WWWLanguage("HTML", "html", "The basic WWW building language.");$html -> displayLanguage();$vbs = new WWWLanguage("VBScript", "vbscript", "ASP's default scripting language");$vbs -> displayLanguage();$js = new WWWLanguage("JavaScript", "js", "The most common scripting language");$js -> displayLanguage();$php = new WWWLanguage("PHP", "php", "The best serverside scripting language in the world!");$php -> displayLanguage();?></body></html>

A class with a method with a name same than it's parent class does execute the method immediatly (what is demonstrated at the code above) :)

Link to comment
Share on other sites

I like PHP objects, you can create multiple instances. Especially the methods is a feature I like.
<html><head><style type="text/css">body{font-family: verdana}a, a:visited{color:#00f}a:hover{background-color:#408}</style></head><body><?phpclass WWWLanguage{	var $name;	var $link;	var $description;	function WWWLanguage($name, $link, $description)	{  $this->name = $name;  $this->link = $link;  $this->description = $description;	}	function displayLanguage()	{  print("<p><a href=\"http:\\\\www.w3schools.com\\$this->link\" target\"_blank\">$this->name</a><br />\n");  print("$this->description</p>\n");	}}$html = new WWWLanguage("HTML", "html", "The basic WWW building language.");$html -> displayLanguage();$vbs = new WWWLanguage("VBScript", "vbscript", "ASP's default scripting language");$vbs -> displayLanguage();$js = new WWWLanguage("JavaScript", "js", "The most common scripting language");$js -> displayLanguage();$php = new WWWLanguage("PHP", "php", "The best serverside scripting language in the world!");$php -> displayLanguage();?></body></html>

A class with a method with a name same than it's parent class does execute the method immediatly (what is demonstrated at the code above)  :blink:

AHHHH.. c..c...code so wrong! :) You have like 5-10 things wrong, you need to move away from javascipt and learn php :blink:heres the list of what you did bad :)
  • To make a variable you dont need to put var $link. Its just $link
  • The target="_blank" jas been deprecated..
  • To call a function you dont put new functionname() in front of it, if you do please correct me.
  • The class and a function in it are named differently, mabye this is where you messed up on the new funtionname() part.To create a new class you would put new classname, to call a function in it you would do *thinks* you know what, im just going to rewrite the half of it :)
    <html><head><style type="text/css">body{font-family: verdana}a, a:visited{color:#00f}a:hover{background-color:#408}</style></head><body><?phpclass WWWLanguage{public $name;public $link;private $description;private function Language($name, $link, $description){ $this->name = $name; $this->link = $link; $this->description = $description;}function displayLanguage(){ echo '<p><a href="http://www.w3schools.com/$this->link">$this->name</a><br />\n'; echo '$this->description</p>\n';}}$html = new WWWLanguage$html->name = "HTML";$html->link = "html";$html->description = "The basic WWW building language.");$vbs = new WWWLanguage("VBScript", "vbscript", "ASP's default scripting language");$vbs->name = "VBScript";$vbs->link = "vbscript";$vbs->description = "ASP's default scripting language";$js = new WWWLanguage("JavaScript", "js", "The most common scripting language");$js->name = "Javascript";$js->link = "js";$js->description = "The most common scripting language";$php = new WWWLanguage("PHP", "php", "The best serverside scripting language in the world!");$php->name = "PHP";$php->link = "php";$php->description = "The best serverside scripting lagnuage in the world";if($selection == "html"){$html->displayLanguage();}elseif($selection == "vbscript"){$vbs->displayLanguage();}elseif($selection == "javascript"){$js->displayLanguage();}elseif($selection == "php"){$php->displayLanguage();}else{echo "please select a language!";}?></body></html>

Link to comment
Share on other sites

One use of objects I especially enjoy is to display information from a database...this is just a relatively primative example.

class MyObject(...variables, excetera...mysql_construct($ResultSet, $row){  ...  builds the object from the result  ...}display(){  ...  returns a formatted version of it  ...}

$Result = mysql_query("SELECT something FROM somewhere WHERE i = 'am1337'")$count = mysql_numrows($Result);print '<table cols="5">';for($i = 0; $i < $count; $i++){    $ThisObject = new MyObject();    $ThisObject->mysql_construct($Result, $i);    print $ThisOBject->display();}print '</table>';

My first programming language was Java, so i'm very used to OO concepts, lol.

Link to comment
Share on other sites

AHHHH.. c..c...code so wrong!  :) You have like 5-10 things wrong, you need to move away from javascipt and learn php :blink:heres the list of what you did bad :)
  • To make a variable you dont need to put var $link. Its just $link
  • The target="_blank" jas been deprecated..
  • To call a function you dont put new functionname() in front of it, if you do please correct me.
  • The class and a function in it are named differently, mabye this is where you messed up on the new funtionname() part.To create a new class you would put new classname, to call a function in it you would do *thinks* you know what, im just going to rewrite the half of it :)
    <html><head><style type="text/css">body{font-family: verdana}a, a:visited{color:#00f}a:hover{background-color:#408}</style></head><body><?phpclass WWWLanguage{public $name;public $link;private $description;private function Language($name, $link, $description){ $this->name = $name; $this->link = $link; $this->description = $description;}function displayLanguage(){ echo '<p><a href="http://www.w3schools.com/$this->link">$this->name</a><br />\n'; echo '$this->description</p>\n';}}$html = new WWWLanguage$html->name = "HTML";$html->link = "html";$html->description = "The basic WWW building language.");$vbs = new WWWLanguage("VBScript", "vbscript", "ASP's default scripting language");$vbs->name = "VBScript";$vbs->link = "vbscript";$vbs->description = "ASP's default scripting language";$js = new WWWLanguage("JavaScript", "js", "The most common scripting language");$js->name = "Javascript";$js->link = "js";$js->description = "The most common scripting language";$php = new WWWLanguage("PHP", "php", "The best serverside scripting language in the world!");$php->name = "PHP";$php->link = "php";$php->description = "The best serverside scripting lagnuage in the world";if($selection == "html"){$html->displayLanguage();}elseif($selection == "vbscript"){$vbs->displayLanguage();}elseif($selection == "javascript"){$js->displayLanguage();}elseif($selection == "php"){$php->displayLanguage();}else{echo "please select a language!";}?></body></html>

Oh?
[*]To make a variable you dont need to put var $link. Its just $link
I learned PHP from a book from the library, it says that to execute code straight, you need to make a method with the name of the class. It also says that you need to use the var keyword in variables in classes. It does still say that you don't need the var keyword outside the class... I just checked the http://www.w3schools.com/tags/tag_a.asp page, if target="_blank" would have been deprecated it would have been written there.I want to execute just the first function and the displayLanguage() after.Besides all, I have tested this out and noted it works. :blink: BTW, what's the difference between public and private variables?
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...