Jump to content
xisto Community
Sign in to follow this  
moonwitch1405241479

Beginners Php - Object Initialization

Recommended Posts

So I got fed up with HTML and wanted to move to dynamic pages... php was THE thing I wanted to learn LOL... SO I started going by a book. I got stuck with Object Initialization.

I don't understand.... I really don't...

To initialize an object, you use the new statement to instantiate the object to a variable. class foo {    function do_foo () {         echo "Doing foo.";     }}$bar = new foo;$bar->do_foo();

What gets me is the given explanation, "you use the new statement" what new statement?? LOL I did fine with arrays, that's all cool. What I get from this piece of code is that you're defining a class called "foo" which consists out of a function "do_foo" which only outputs a string "doing foo.". But where in THAT lil piece of code are you creating a new object? The second part.. $bar = new foo; Isn't that wrong code? I mean no single or double quotes? And on last line I am fully lost.

Share this post


Link to post
Share on other sites

I don't understand.... I really don't...

Hopefully you will see some "light" by the end of this :P

 

 

To initialize an object, you use the new statement to instantiate the object to a variable. class foo {    function do_foo () {         echo "Doing foo.";     }}$bar = new foo;$bar->do_foo();

We'll proceed according to your example. Lets take up your first question.

 

What gets me is the given explanation, "you use the new statement" what new statement?? LOL I did fine with arrays, that's all cool. What I get from this piece of code is that you're defining a class called "foo" which consists out of a function "do_foo" which only outputs a string "doing foo.". But where in THAT lil piece of code are you creating a new object?

Take a second look at your code - the second last line where it says, $bar = new foo; - that's where you're using the "new" statement to create an object that is of the type foo. This statement simply creates a variable (or you can call an OBJECT) that inherits the properties of the class named "foo". That $bar = new foo does exactly that. "new foo" tells the parser to create the object based on class "foo" and then assigns is a commonly usable name - which in this case is your variable, $bar.

 

The second part.. $bar = new foo; Isn't that wrong code? I mean no single or double quotes? And on last line I am fully lost.

<{POST_SNAPBACK}>


Nope. That's perfectly all right. Read what I wrote above. Now look back at your class. What does it contain ?? Just ONE function that prints the "Doing foo" line.. right ? Here's the whole idea of classes and objects.. A class is a template - a blueprint, based on which you can create objects, which immediately inherit all the properties of the class. What are class foo's properties here ? Nothing but that function named do_foo. If that foo class had some other variables & functions declared within it - even they'd be considered among the properties of that class.

Now since you declared $bar to be an object of the type, class foo - it should inherit the properties of the class - it does so in this case. $bar now contains that funtion do_foo. But how do you call that function in $bar.. That's where the last line comes to play.

$bar->do_foo(); -- That -> sign that you see after $bar, simply means that the statement following it, is a member of that object.. So the parsers looks into the object and finds the right function (in this case do_foo) to call. If your class had public variables like $var1, $var2 .. even they could be refered to as, $bar->$var1, $bar->$var2 ... etc.. Replace the "->" with a dot "." and see if that rings any bells...

If you've coded in .NET/Java you'd know ... how sometimes functions within certain packages are called in the form, classname.functioname e.g. Microsoft.VisualBasic.Left() .. the "->" works in the same way as that "."

 

Hope this will help you.. at least partially. :P

Share this post


Link to post
Share on other sites

Wow, why did you stop typing? I'm beginning to understand now. That's the easiest to understand explanation I've seen so far. Still a little fuzzy on whay, but I'm beginning to understand how. I think I'll start playing with this some more and hopefully get it figured out. moonwitch, I'm glad you brought the subject up again, my post on the subject has gotten a little stale. I hope we both figure it out.Happy initializing, :P vujsa

Share this post


Link to post
Share on other sites

Wow, why did you stop typing?

 

I'm beginning to understand now.  That's the easiest to understand explanation I've seen so far.  Still a little fuzzy on whay, but I'm beginning to understand how.  I think I'll start playing with this some more and hopefully get it figured out.

 

moonwitch, I'm glad you brought the subject up again, my post on the subject has gotten a little stale.  I hope we both figure it out.

 

Happy initializing,  :P

 

vujsa

<{POST_SNAPBACK}>

I didn't stop trying, I let it lay next to me. If I get tired and frustrated I am not very good moodish :P (It's probably a woman thing) But I read M^e's explanation, especially the "." part about -> helped me, because Delphi worked similar. I also printed the thread :o

 

I do feel the example used in the book (with do_foo) is really a very poor one. It would be more handy in some situations, however I have no idea how to think of one as of yet LOL Here's how I get it...

 

<?php  class smilie {    function make_smile () { [tab][/tab] echo "a joke ";  }}$funny = new smilie;$funny->make_smile();echo "$funny";?>

The output of this is "a joke Object" without the quotes. I was trying to get this to work, but I got errors...

 

<?php$joke="hahahaha";  class smilie {    function make_smile () { [tab][/tab] echo "$joke";  }}$funny = new smilie;$funny->make_smile();echo "$funny";?>
But that gives an error "Notice: Undefined variable: joke in C:\Program Files\Abyss Web Server\htdocs\PHP\joke.php on line 11

Object " I also tried to put the $joke in the class but that stays fairly the same. So there's still something missing LOL

 

For the record the first piece of code, was my first try EVER at php!!!

Share this post


Link to post
Share on other sites

Please read this line again:

Wow, why did you stop typing?

<{POST_SNAPBACK}>


I was asking why m^e didn't continue with his expaination. Sorry, I have a very sarcastic sense of humor.

 

You think your book's example was poor, did you see the one @ PHP: Hypertext Preprocessor Website

 

By the way, I think it is funny that you wrote a joke script because I just wrote one too. Did you cast a spell on my avatar? :P

 

 

 

I think I know what the error is about, but I think I should let someone else aswer because I can't completely answer the question and I'm also trying to learn this.

 

vujsa

Share this post


Link to post
Share on other sites

I'm not 100% sure, but if php operates as much like c++, java, and other programming languages of that style, then the issue is variable locality. Variables, unless declared otherwise, are local to the function they are declared in. This allows you to use common variables, such as $count fir counting, in many different functions without worrying about overwriting the value in another function. Now, to look at your code:

<?php$joke="hahahaha"; class smilie {   function make_smile () {  echo "$joke"; }}$funny = new smilie;$funny->make_smile();echo "$funny";?>
You have two separated functions here. The first is the main function which begins executing when the script executes. The second is make_smile(). Because $joke was declared in the main function, it is local to the main function. This means that make_smile() does not have access to it.
The reason why the problem persists when you place $joke in the class is the special way of accessing class variables. You must use the -> to access the variable. So to access the variable in this example you would use $funny->$joke (keep in mind that this paragraph assumes we have moved $joke inside the class). To make the function general to any instance of the class, we use the "$this" identifier. "$this" refers to the object the function belongs to, so "$this->$joke" accesses the $joke variable for a the specific instance of the class that has called the function.
You were also looking at the wrong section in the PHP manual for information on classes. You were looking at the explanation as a type (a type is a group of variables and/or functions that can be used as a special variable). What you needed to be looking at is the explanation of classes here: https://www.cica.es/comu/php3Doc/oop.html/

~Viz

Share this post


Link to post
Share on other sites

Hey moonwitch,

 

I not sure whether the book stated what you say or not, nor am I going to say they are right or wrong but the problem is $joke exists outside the function, it's not global either, but if the book suggests this as an example, then it's quite possible they work with global which was default on older PHP versions and that these variables have access from anywhere in the program.

 

How I like using classes is creating functions to set the variables but in this case I'll leave that out and just explain the problems.

 

First problem is the variable outside the object, outside the function as well.

 

<?php

 

class smilie

{

var $joke;

function make_smile()

{

echo $this->joke;

}

}

 

$funny = new smilie;

$funny->joke = 'hahaha';

$funny->make_smile();

 

?>

 

That's how I would do this example (well keeping as close to the original code), everything is inside the Object, we create our new object, have access to the object variable $joke but we must call it through our Object not through it's variable name, I also use the $this variable, which is a variable used to store the current object that called it.

 

If you wanted to do it your example way, that's also easy enough, but it needs a few adjustments.

 

<?php

$joke = 'woohoo';

 

class smilie

{

function make_smile($joke)

{

echo $joke;

}

}

 

$funny = new smilie;

$funny->make_smile($joke);

 

?>

 

See we needed to pass the $joke contents with our function, so that it can reside inside, however the creation of function make_smile($joke), the $joke part of this is not the same as the $joke bit we set at the beginning, we could have said function make_smile($joke2) and tried printing $joke and it wouldn't work because $joke does not exist in that function, but if we printed $joke2 out it would work, the $joke we passed in our function becomes make_smile($joke2 = $joke); so now $joke2 holds the contents of what $joke has, but it still doesn't have access to our $joke variable.

 

Cheers,

 

 

MC

 

p.s. Thought I'll add how I'll actually do this class

 

<?php

 

class smilie

{

var $joke;

 

function addJoke($joke)

{

$this->joke = $joke;

}

 

function make_smile()

{

echo $this->joke;

}

}

 

$funny = new smilie;

$funny->addJoke('hahaha');

$funny->make_smile();

 

?>

 

What gets me is the given explanation, "you use the new statement" what new statement?? LOL I did fine with arrays, that's all cool. What I get from this piece of code is that you're defining a class called "foo" which consists out of a function "do_foo" which only outputs a string "doing foo.". But where in THAT lil piece of code are you creating a new object? The second part.. $bar = new foo; Isn't that wrong code? I mean no single or double quotes? And on last line I am fully lost.

<{POST_SNAPBACK}>


moonwitch, you have to understand, that to use an object you can't use the object directly, you must give the object it's own storage, the object is just a set of instructions, it's not a variable you can call on.

 

so when you do

 

$bar = new foo; you are actually storing all the instructions for foo inside of bar, which is pretty much the whole object.

 

single or double quotes, $bar = "new foo"; is actually a string of characters not what we were intending on doing, which is creating a new object inside our variable $bar;

 

The last line pretty much uses your new object you created and calls the function do_foo();

 

Imagine this, but don't take it in, the class foo, foo->do_foo(); foo is the object, foo calling do_foo(); is our object calling the function, now we replaced foo (the object) with our variable $bar, so now $bar is now the new object replacing foo's position, just remember, foo is only a set of instructions for whatever variable wants to take it on, else it's just code that doesn't get used at all.

 

We could write a lot of code within our program, that never gets used at all, but if we wanted to we could use it, because it exists. Classes are pretty much libraries of code we would create to do specific things, but we would actually distribute it as a library of functions, instead of actually writing it within our code, we would just include it.

 

So if I had a class that created HTML pages, (this class does exist), I would include that class, create a new object to use this class and then work with that, all I would really need to know, is what functions exist and what to pass within those functions of this class to actually use it, I should not need to know what variables it creates, nor have to worry that the variables used in this class will conflict with my own program variables, since those variables are contained inside the class only. (well not worrying about the variables should be something, because usually we create functions to take care of initialising the variables, not actually doing it ourselves).

 

e.g. We might have a function that sets the title of our page and it might be a function called setTitle($title) { $this->Title = $title; } and that's it, the function set our titlte for us just by us calling the function to do this $object->setTitle('My Title');, this is how our classes should be done.

 

MC

Share this post


Link to post
Share on other sites

Well well.. both MC and vizskywalker have done a damned good job of explaining the nuances of classes & objects - so no need of delving any further. I'll try come up with a tut. of variable scope and what you can/cannot do with objects though. Lets see if that helps you guys out. :P

Share this post


Link to post
Share on other sites

I don't really see the use of a class... Or am I just being dumb?

because according to php.net a class is

A class is a collection of variables and functions working with these variables.

Because you can also do this (with the example of moonwitch)

  function do_foo ()   {       echo "Doing foo.";   }  do_foo();

Or am i missing the point here :S ?

Share this post


Link to post
Share on other sites

A class is used mainly when you need to define a whole bunch of different types of data for repeated times. Like in a game, the army system at Xisto. Each member of that game has several variables, money, rank, troops, etc. There are several functions that each player can perform, attack, buy troops, buy weapons, etc. So if we make a class for a player, it may look something like this:

class player{ var $rank; var $troops; var $money; function buytroops($number) {  $this->$troops += $number;  $this->$money -= ($number * 2500); } function displaystats() {  echo "rank: $this->$rank";  echo "troops: $this->$troopd";  echo "money: $this->$money"; }}

Now, imagine if we had 300+ of those classes, one for each player, that is only 300 variables to keep track of. However, if we didn't use classes, then we have three variables repeated for >300 players for a total of 3 * 300+ = 900+ variables to keep track of. Classes simplify things greatly. BBy placing the functions in the classes. we allow that player to change the data without haveing to make the data accessible to any player, thus preventing many accidental changes.

~Viz

Share this post


Link to post
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
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.