...

View Full Version : Oop



SDP2006
12-22-2003, 03:38 PM
Can someone explain OOP to me and give me the most simplest example? I would really appreciate it. Thanks.

me'
12-22-2003, 04:12 PM
At it's simplest form, Object Orientated Programming (OOP) is just trying to use objects with data members and functions instead of a lump of variables to save time and code bloat. I don't know much about it in PHP, but all new programming languages are based around OOP (C++, Pascal is now, BASIC, Java). The very first OOP language was Simlua-67, created in Scandinavia to aid in solving modelling programs, but the language that made it famous was Smalltalk, which completely revolutionised the programming world.

The three features that every object orientated language should have are: Inheritence (being able to 'inherit' a new object from old, giving the inherited object access to all its parents members)
Function overloading (creating several functions of the same name but with different arguments, the compiler will chose which function to run at runtime).
Virtual functions, also called polymorphism or late binding (kinda complicated but basically having overloaded functions in different levels of inheritance, and the compiler chooses which one to run at runtime after perfoming an upcast -- calling a function with an object which is an ancestor of that specified in the argument list)I wouldn't be very good at providing examples, but I did a quick Google search and here are some Java examples (http://www.cs.cornell.edu/courses/cs100/2000sp/examples.htm).

If you want an extremely simple one (in C++):
class obj {
int randomnumber; //data member
char* randomstring; //data member
int randomfunction(char* c){return 1;}; //function member
obj() {randomnumber = 1; randomstring = "hello world";} //constructor
~obj() {randomnumber = 0;} //destructor
obj(obj& o) {o.randomnumber = 1} //copy constructor
}All objects have a constructor (called when the object is created), a destructor (called when the object is destroyed) and a copy-constructor (called when a new object is created from an existing one). If any of these don't exist, the compiler will create default ones for you.

Now we have an object, obj that we can create new instances of with the constructor, do stuff with using the member functions, and read and write to the data members.

Celtboy
12-22-2003, 04:56 PM
LOL. I knew I shoulda saved my 3000 line tutorial. Here's a quicky example.


First of all, one of the ideas behind OOP is that code is placed in reusable chunks. This code is then used to create an object; the object can be manipulated, made to do things, etc.


So before you actually "create an object," you design the template for the object. This template is called a "class." All code that the object does, and properties of the object is placed inside the class. I'm going to use PHP for this, since you've placed the thread here in the php forum ;)


<?php
class Student {

} ?>

The name of our sample class is "Student." What we want to do is create the template for a typical "student." The student can do things. Some of the things the student can do would be, uhm, go to class, skip school, go to lunch, turn in homework, ride the cheesewagon (er bus), that kinda thing. Anything we want the typical student to be able to do, we put inside a function. (aka methods).

Continuing with our example:

<?php
class Student {

function goToClass() {
}

function rideTheBus() {
}

function skipSchool() {
}
} ?>

Ok great. Now our template has some basic actions our student can perform.

Every property we want assigned to the student is also placed in the class. Properties might include the student's name, their grade level, their gender, their schedule, etc.

On to the example:


<?php
class Student {

var $Name;
var $Gender;
var $GradeLevel;
var $Schedule;

function goToClass() {
}

function rideTheBus() {
}

function skipSchool() {
}
} ?>

Ok... so we've created the variables in our template. Unfortunately, nothing is actually assigned to the Student; we just have empty variables.
You assign the values using the "this" keyword. Also, if you have a function called the same thing as the class name ("Student"), then when you create an "instance" of the object in your code (ie, you create a student in your application), then that function is called automatically, as soon as you create the object. This function has a special name, called a "constructor".

I'll get to the example in a second. I also need to mention, that functions can take "arguments" or "parameters." These are values, passed into the function. The function assigns these values to variables. The values are passed in via the parenthesis of the function.


Back to our example:


<?php
class Student {


/* These are some of the properties */
var $Name;
var $Gender;
var $GradeLevel;
var $Schedule;

/* Constructor. Called as soon as we create a student */
function Student($studentName, $studentGender) {
$this->$Name = $studentName;
$this->$Gender = $studentGender;
}

function goToClass() {
}

function rideTheBus() {
}

function skipSchool() {
}
}?>

What did we do? Well we added a constructor, and we told it to accept to parameters. These parameters are assigned the variable names of "$studentName" and "$studentGender." Now, these two variables can only be used INSIDE THIS FUNCTION. That's called variable scope.

The next two lines of code say "I want to take the values passed into this function, and assign them to the object." What does that mean? Well it means that when you create the object now, you can access $Name, and $Gender.

More example....


<?php
include "Student.php";

$a_student = new Student("John","Male");
?>

I kept it simple.
The first line just makes sure that our template (the class file) is accessible.
The second line is where the magic happens. It creates a new instance of the Student object (this is called instantiation), and passes two values to it - "John" and "Male".
You create instances of objects using the "new" keyword. The syntax is as follows:

variable = new ObjectName(parameters)

Remember that when we create the object, the constructor function is already called. Our constructor wants two values, the student name, and the gender. For that reason, we passed these values in as we created the object.

So we've got a student. What do we do with him? Step 1:


<?php
include "Student.php";

$a_student = new Student("John","Male");
print $a_student->$Name;
?>

everytime you access something in an object you create (in php), you use the "->" characters. Some programming languages use periods. It depends on the language. (As an example, if you created that same object in JAVA, you'd print the "$Name" property by typing:

System.out.print(a_student.Name);
.. in java, you use "System.out.print" instead of just "print", like in php)

So we have an object. How do we make him do the things we created in our template? (ie the functions). Well once you've added some code to the functions, you can make the object perform those function by doing the following:


<?php
include "Student.php";

$a_student = new Student("John","Male");
print $a_student->$Name;

$a_student->goToClass();
?>

That last line tells the Student object to call the function goToClass. Now where's the benefit? What if you wanted to create lots of students? An example:


<?php
include "Student.php";

$a_student = new Student("John","Male");
$b_student = new Student("Mary","Female");
$c_student = new Student("Larry","Female");

print $a_student->$Gender;
print "<br>";
print $b_student->$Gender;
print "<br>";
print $c_student->$Gender . " " . $c_student->$Name;

?>

That code creates 3 students. It then prints out the first two student's genders. It then prints the third student's Gender and his...er....her ;) name.

Seeing the benefits? You could then make b_student goToClass, and maybe have c_student skipSchool. These are spiffy things your program can do.

Of course, you could write a "changeGender()" function....it would like like this:


...
function changeGender() {
if ($this->$Gender == "Female") {
$this->$Gender = "Male";
} else {
$this->$Gender = "Female";
}
}
...


hehe. place that code in the class, and whenever you want to perform a sex change, just ....


...
$a_student->changeGender();
...


(the ... indicates code above and below, but I left it out for brevity).


Now, any function can accept parameters, you just add that to the class, and then when you call the functions, you pass the values in. Let's say we were to rewrite our "rideTheBus()" function..... to....


...
function rideTheBus($busNumber) {
$statement = $this->$Name . " rides bus number " . $busNumber;
return $statement;
}
...

then in your code....(the main program)....

...
print $a_student->rideTheBus("65");
...

So...what'd we do? well in the rideTheBus function, we told it to accept a value, and place it into the variable $busNumber. We then created a statement that says the student's name, followed by the words "rides bus number" and then the value placed in $busNumber.

The return statement says that when that function is called, return the value in $statement.

We then passed bus number "65" into the function. The result of the above code would be to print out the following:

John rides bus number 65.

Now, we didn't have to do this:

...
print $a_student->rideTheBus("65");
...

(that simply says "print the value RETURNed by the function rideTheBus()).

We could have done this:

...
$busRideStatement = $a_student->rideTheBus("65");
print $busRideStatement;
...

This code does the same thing, but first dumps the sentence into the $busRideStatement variable, so we could reuse it later by just calling the variable, rather than having to recall the function.



That, my friend, is OOP in a nutshell. It's just the basics.
The terms you should be familiar with:
parameters
functions
class
constructors
variable scope
return statements

This is by no means comprehensive. Some advanced topics include:
passing by reference
destructors - (just a special function, called when you destroy your object)
polymorphism
inheritance


I'm sure there are other terms I'm not remembering right now. Let me know if that was a good enough explanation. The complete code of what we did is below:

File: Student.php

<?php
class Student {


/* These are some of the properties */
var $Name;
var $Gender;
var $GradeLevel;
var $Schedule;

/* Constructor. Called as soon as we create a student */
function Student($studentName, $studentGender) {
$this->$Name = $studentName;
$this->$Gender = $studentGender;
}

function goToClass() {
}

function rideTheBus($busNumber) {
$statement = $this->$Name . " rides bus number " . $busNumber;
return $statement;
}

function skipSchool() {
}

function changeGender() {
if ($this->$Gender == "Female") {
$this->$Gender = "Male";
} else {
$this->$Gender = "Female";
}
}

}?>

file: index.php

<?php
include "Student.php";

$a_student = new Student("John","Male");
$b_student = new Student("Mary","Female");
$c_student = new Student("Larry","Female");

print $a_student->$Gender;
print "<br>";
print $b_student->$Gender;
print "<br>";
print $c_student->$Gender . " " . $c_student->$Name;

print $a_student->rideTheBus("65");

$c_student->changeGender();
print $c_student->$Gender; // this will print "Male" now...

?>

I hope that helps!

-------
(9995 characters long!!! (minus this statement...heehee))

firepages
12-22-2003, 05:19 PM
Originally posted by me'

The three features that every object orientated language should have are: Inheritence (being able to 'inherit' a new object from old, giving the inherited object access to all its parents members)
Function overloading (creating several functions of the same name but with different arguments, the compiler will chose which function to run at runtime).
Virtual functions, also called polymorphism or late binding (kinda complicated but basically having overloaded functions in different levels of inheritance, and the compiler chooses which one to run at runtime after perfoming an upcast -- calling a function with an object which is an ancestor of that specified in the argument list)


note that what makes a languare a 'real' OOP language is debatable at best and the source of many a fight ;)

e.g. PHP does not support function overloading in the traditional sense , nor can it ever since PHP is typless .

however with PHP's impressive function handling functions and the ability to cast & test for types you dont strictly need it.

Other common debates revolve around multiple inheritance ,which PHP does not have (nor will it ever) vs agrregation/composition which it does.

....................

Note that PHP5 will spearhead the OOP revolution for PHP as it brings with it all the things that make JAVA heads happy eg public , private & protected variables , abstract classes and methods , destructors and so on.

It will still be missing Interfaces which many seem to pine for and nearly made it in & no namespaces which will definately annoy the JAVA heads which can only be a good thing (sorry Spooks ;))

Note that its fair to say that all the new OOP features with PHP5 can currently be 'simulated' in PHP4 to one extent or another , basically PHP5 will just make life a little easier/quicker and code a little more obvious.

mordred
12-22-2003, 08:26 PM
Originally posted by firepages
Note that PHP5 will spearhead the OOP revolution for PHP as it brings with it all the things that make JAVA heads happy eg public , private & protected variables , abstract classes and methods , destructors and so on.


Not to forget: Exception handling. Finally. ;)



It will still be missing Interfaces which many seem to pine for and nearly made it in & no namespaces which will definately annoy the JAVA heads which can only be a good thing (sorry Spooks ;))


Interfaces have been removed from PHP5? What a pity. I'm seriously considering developing more in Java if the new OOP of PHP5 is as half-baked as the one of PHP4 was/is.



Note that its fair to say that all the new OOP features with PHP5 can currently be 'simulated' in PHP4 to one extent or another , basically PHP5 will just make life a little easier/quicker and code a little more obvious.

Uhm... how do you simulate interfaces, without multiple inheritence? :D

SDP2006
12-22-2003, 10:13 PM
Thanks for the replies. Especially celtboy's.

I have a better grasp of it now. Thanks

Anymore replies are welcome.

firepages
12-23-2003, 02:52 AM
Uhm... how do you simulate interfaces, without multiple inheritence?

well since many will suggest that multiple inheritance is OOP gone wrong .... ;) , and PHP is never ( & not alone in this ) going to support them ..

interfaces in PHP5 were basically going to be `super-abstracts` that defined requirements of all derived classes , now since we do have true abstract classes we can simulate that + since you can simulate those (at a price) abstract classes in PHP4 I think I was almost justified in my statement :D

not that I would fancy trying to implement such.
why they did not make the cut I don't know , I did see stuff on the internals list about why but it flew right over my head (again)

So I do not think that PHP5's OOP is half-baked , they have done what they could without breaking anything and without compromising performance which is a much more important consideration in an interpreted language, as you mentioned (and I totally forgot~ ) exception handling alone is worth it for many!

PHP is never going to be .NOT or JAVA where everything is an object , and if it was then it would be pointless as .NOT or JAVA would be better suited.

No other interpreted language has the power and flexibility AND speed that PHP5 promises , yes it is a jack-of-all-trades , but with few compromises in most departments.

So I agree that interfaces would have been nice (If only to attract JAVA heads to the light side ) as would namespaces , but I can live with it.

SDP2006
12-23-2003, 03:50 AM
So, know that I understand it, what are some of the uses for OOP?

Thanks

Celtboy
12-23-2003, 04:05 AM
General in practice:

Reusable chunks of code. Ability to easily manage code.

Now, in theory, everything you code should be in a class. Well. in theory.

As for practical applications-

Strings are an excellent example. Every string variable you create is an object. You can manipulate that object via String object functions (methods) too. the like parsing functions, getting the string length, etc.

A few useful applications where I've used objects:

An online help desk system. The ticket system itself is an object. When the user logs in, he's an object. Here's a great reason. That user object can be stored in a cookie or in a session. Then on subsequent pages, rather than trying to dig random variables out of the $_POST or $_GET, you can simply pull out the object....and guess what? the functions are still there...and so are the properties that you've assigned! You can create the aforementioned user object, and then, on the "change password page", you can access the $theUser->$password. That's a GREAT ability.

The tickets, are also objects.

A content management system:
the User is an object.
every template is an object. (this is great, as object classes are basically templates themselves!)
every page is an object.
the system is an object.

Those are a few real-world uses.

mordred
12-23-2003, 04:28 AM
Originally posted by firepages
well since many will suggest that multiple inheritance is OOP gone wrong .... ;)


I might agree with this statement, but having only short experience with the pitfalls of multiple inheritance I'd say I'm not really qualified to justifiy this decision. Maybe MI makes sense at certain points. But I digress.



interfaces in PHP5 were basically going to be `super-abstracts` that defined requirements of all derived classes , now since we do have true abstract classes we can simulate that + since you can simulate those (at a price) abstract classes in PHP4 I think I was almost justified in my statement :D


Hmh.... NACK! :D
That's not how interfaces work, at least not in Java. The difference is that an abstract class must fit somewhere into an inheritance tree whereas an interface (or many) can be added to a single class deep down in the tree, without touching upon the structure of that tree. Of course, in a statically typed language like Java it's much more important to have the ability to refer to an object by it's interface type, in PHP that's a non-problem.



why they did not make the cut I don't know , I did see stuff on the internals list about why but it flew right over my head (again)


I just searched the MARC archives, and couldn't find anything related to the withdrawal of interfaces from PHP5. Sebastian Bergmann asked a week ago about a problem with interfaces inheriting from a common ancestor, as he was trying to port a Java framework to PHP, so I suppose that interfaces must be still present in some form.

Bah, I'm just installing the new PHP5 beta on christmas and look for myself. That's why I got those paid holidays for, right? :)



So I do not think that PHP5's OOP is half-baked , they have done what they could without breaking anything and without compromising performance[...]


I was teasing with my "half-baked" statement. The OOP support in PHP4 is often just "good enough"(TM), at least until now it was for me. Lately although some concepts, which (hopefully!) will come in PHP5, have been missed and would have simplified things. Like exceptions. Dealing with 1.001 different error-reporting schemes while integrating components of different vendors is a royal PITA.



PHP is never going to be .NOT or JAVA where everything is an object , and if it was then it would be pointless as .NOT or JAVA would be better suited.


Ironically, PHP shines in one area (PHP arrays vs. Java collections) where it's much more cumbersome to program in Java because in the uber-OOP language Java, there are some things that aren't real objects (the primitives like int, char, boolean). :)



No other interpreted language has the power and flexibility AND speed that PHP5 promises , yes it is a jack-of-all-trades , but with few compromises in most departments.


No other is of course a wide claim, but I tend to agree with this statement.

Sorry Stevie for hijacking your thread a little, but we stayed close on the yet very general topic. I hope the discussion between me and firepages so far was not totally futile for your research into OOP.

mordred
12-23-2003, 04:38 AM
psst celtboy: You have one repeating typo in your examples. To access a member variable you don't write

$obj->$memberName

but rather

$obj->memberName

without the second dollar sign, unless you intended to use variable variables at these points (unlikely).

:thumbsup:

firepages
12-23-2003, 04:55 AM
nice toot BTW Celt !

, adding to your last post...

..eg protocols , I recently had to add https to an existing site , were the code not OOP (or with a very well structured set of functions) I can imagine I would have been digging through the several thousand lines of code for several hours , then spending another several testing and debugging , now since all my URL's were formatted by a class method(function) it took literally minutes to alter that method to add https capabilities to the whole site , I still had to do some testing but only need to concern myself with one source file.

However the advantages of OOP tend to avoid you until suddenly one day it hits you like a brick and it all falls into place , and you wont get that brick coming your way until you have played with OOP for a while .. thats just the way it works , especially if you are from a non OOP background.

..........................................


However in IMO OOP is often overused in PHP.

OOP carries an overhead , procedural code will be much faster than Object Oriented versions of the same , at runtime if not in development (and your code will be run many more times than it will be developed)

I tend to use OOP more for administration code than runtime code , eg I have my own frameworks that are OOP but actually create procedural code for use per page view.

same same with PHP templating systems , they offer great flexibility but slow performance so its important to try and cache that , the same logic goes (for me) with OOP

remember that JAVA and .NOT are compiled languages (to a point (byte-code then interpreted ;))) , the overhead of OOP is less important in a compiled application , PHP is interpreted so more efficient code is required.

I personally would also avoid the JAVA'fication of PHP , eg classes for string methods etc I see as pointless , PHP IS the std class object with a whole pile of built-in string methods , further abstration of such seems pointless to me though there are many people working on cloneing JAVA & .NOT classes so I guess its a personal preference (I just reckon I am right ;))

Celtboy
12-23-2003, 06:18 AM
::jumps into the pot::

thanks for the nudge, mordred....i hadn't noticed. *oopsie* ;) I use a LOT of variable variables, but you're right, I didn't mean to use them there.

Thanks....that tutorial was written at work, amidst quite a bit of annoying coworkers and random chaos. So if you find anything else that's screwed up, by all means, lemme know!

Re: The Javafication of PHP

The eloquent are able to say things in simple, concise points. The frustrated usually have difficulty saying what they want. The outright mad just go off, while the indifferent sit back and watch.

Me? I'm somewhere in the midst of it all.

1. Firstly, it seems theere are issues regarding whether or not the new features of php5 are, in fact, enhancements. I think there are valid points on both sides. Yes, more advanced programming technologies are exactly what many php developers have been waiting for. On the other hand, as firepages has clearly put, it may cause performance issues. My vote goes to performance here. It's been PHP strong's point for a long time. While I won't go on a tirade regarding the merits of procedural code and OOP, I think firepages is right- too much emphasis on unneeded system code may cause unncessary performance hits.

2. Secondly, the other languages firepages mentioned, are compiled as he said. While valid, there have been some discussions regarding making a compiled version of php. I could easily see a cult group making this happen. Add a few window controls and a truly robust external dll handling system, and PHP will take on .net (c#). My gut feeling - stick with interpreted engines, and therfore - code to that.

3. OOP *will* hit you like a ton of bricks. I've written a plethora of web apps, only to revisit the code later and scream in horror. I've attempted to convert many of those apps to OOP from procedural, only to trash all the code, and start anew. If you can begin your coding education with OOP, you'll see the relevance later.


4. I'd like to see some PEAR integration. And perhaps some of that universal db stuff going. I mean, does it REALLY need mysql_query(), postgresql_query(), etc? Welcome to the world of WRAPPER FUNCTIONS.....or something. ;)

lol

firepages
12-23-2003, 10:41 AM
Celt on #2

its already possible if not easy , there is the bcompiler in PEAR which compiles to PHP-byte code , put that together with the embed.sapi and you can conjure(sp?)-up a 'compiled' executable , in reality its more like the JVM interpreting JAVA byte-code but nearly there , + I see that delphi now lets you use PHP extensions in one form or another but I have not a clue how ?

& there are a fair few PHP-2-C type projects bobbing around , so I totally agree that one way or another PHP's future lies not only on the web-server , but on your PC or MAC as well.

I can't wait for the GTK2/Zend2 port of PHP-GTK , its happening now but probably a few months off yet (got to get PHP5 stable first) , and PHP5 brings a whole heap of advantages to PHP-GTK as well since all of it is totally OOP .

.......................................

Mordred on Interfaces

I won't even try and argue with you on those as you will have far more experience than myself there , but in PHP I was under the assumption that an Interface was basically a set of rules for any classes that were 'derived' from it , in essence a base class (I know its not a class as such but I do not have the words!) that enforced any derived classes to require certain methods and perhaps properties , that was my take on the PHP implementation at least but that was gathered from bits and bobs from around the net and the lists so I if its total yak then so be it :D

anyway I would still assume you could have an interfaces implementation with no MI :D


No other is of course a wide claim, but I tend to agree with this statement.


well a little bias I suppose ;) I know that Python and Ruby are almost contenders and PERL moreso , certainly PERL would win in some quarters but as a whole I still think its about right even without my personal bias.



Bah, I'm just installing the new PHP5 beta on christmas and look for myself. That's why I got those paid holidays for, right?

I think thats the reason :D , good stuff , I have been avoiding PHP5 as my head is still getting round some PHP4 concepts :D

SDP2006
12-23-2003, 11:42 PM
Now, I have this code


<?php
include('config.php');

class Header {

function Header(){
echo "<div style=\"border: 1px solid $bordercolor; background-color: $headerbgcolor; color: $textcolor; padding: 5px;\">";
echo "<font size=\"6\"><b>$websitename Guestbook</font><br><font size=\"4\"><a href=\"enter.php\">Add Entry</a> ~ <a href=\"admin.php\">Admin Area</A></font></b><br>";
echo "<br></div>";
}
}

?>

What do I need to do to have in my script to make it echo function Header() ? I'm trying to make a template like system instead of having to put the
echo "<div style=\"border: 1px solid $bordercolor; background-color: $headerbgcolor; color: $textcolor; padding: 5px;\">";
echo "<font size=\"6\"><b>$websitename Guestbook</font><br><font size=\"4\"><a href=\"enter.php\">Add Entry</a> ~ <a href=\"admin.php\">Admin Area</A></font></b><br>";
echo "<br></div>"; in every file.

Thanks

Thanks

Celtboy
12-24-2003, 12:39 AM
Erm, I don't think you can use "Header" as a valid name - PHP has that one reserved....just rename it...

to like... class myHeader


then:



...
$header = myHeader();
...


because you have it printing in the constructor, it will print when you create the object.

SDP2006
12-24-2003, 02:39 AM
Now, I have this


<?php
include('config.php');

class iHeader {

function iHeader(){
echo "<div style=\"border: 1px solid $bordercolor; background-color: $headerbgcolor; color: $textcolor; padding: 5px;\">";
echo "<font size=\"6\"><b>$websitename Guestbook</font><br><font size=\"4\"><a href=\"enter.php\">Add Entry</a> ~ <a href=\"admin.php\">Admin Area</A></font></b><br>";
echo "<br></div>";
}
}
$header1 = new iHeader();
print $header1->iHeader();
?>

No error, but it prints nothing. Any help?

Thanks

stuntboy
12-24-2003, 05:10 AM
Disclaimer:
I avoid OOP like the plauge so there may be a couple errors in what I say

Ok there is a couple problems...

Since you have the function inside the object named the same as the object it is a constructor so will be called automatically when the object is created (hence being a constructor)

What you have now prints twice for me. once when you create the object and once when you call the method (the function) specifically.

So if you dont want the method to be called automatically upon the objects creation you should name it something else.

Also:
print $header1->iHeader();

the print is kind of redundant since you are already saying to echo in the function. $header1->iHeader(); would print all on its own

firepages
12-24-2003, 08:10 AM
hi , firstly its generally frowned upon to put too much (some say any) HTML or markup in your classes , but thats something to discover down the tracks... of course if a classes primary job is to output HTML as here, then thats different ! :D

as Stunt suggests , you often don't want the constructor of your class (the function that shares the same name of the class) to do much but perhaps setup some class variables , or preperation work , of course sometimes you do , but here probably not , take a look at ...



<?php

class html_common{
function html_common( $style='' ){//optionally pass a style//
$this->style = (!empty( $style ) ) ? $style : 'default_style' ;
return true ;
}

function header_main(){
$str = '<div id="' . $this->style . '" class="header">da header</div>' ;
return $str ;
}

function footer_main( ){
$str = '<div id="' . $this->style . '" class="footer">da footer</div>' ;
return $str ;
}
}

$yaks = new html_common(); //or say $yaks = new html_common( 'blue_style' ) ;
/* note we echo here not in the method itself */
echo $yaks->header_main();
echo $yaks->footer_main();

?>


here the constructor optionally takes an argument but does little else , then your class methods actually do the work.

another point to note is that echo'ing from within your class methods should mostly be avoided unless its for debugging purposes , so try when you can , to

return $return_value ;

as above or use references which are perhaps best ignored for now !

now you can add methods to your class as and when required or say different HTML elements

SDP2006
12-24-2003, 03:15 PM
Thanks so much firepages, it works now, but one more question


<?php
include('../config.php');
?>
<html>
<head>
<title>Admin Area</title>
<style type="text/css">
body { padding: 20px; }
#header { border: 1px solid black;
background-color: <?php echo $headerbgcolor; ?>;
color: <?php echo $textcolor; ?>;
padding: 5px;
font-family: Tahoma;
}
</style>
<?php
class html_common{
function html_common($style='' ){//optionally pass a style//
$this->style = (!empty( $style ) ) ? $style : 'default_style' ;
return true ;
}
function header_main(){
$str = '<div id="' . $this->style . '" class="header">da header</div>' ;
return $str ;
}

}

$yaks = new html_common('header');
/* note we echo here not in the method itself */
echo $yaks->header_main();

?>

I have a variable in config.php called $websitename. I can't get it to echo in header_main()

Can you show me how? I want it to be in the div of header_main()

Thanks

mordred
12-24-2003, 04:04 PM
The normal scoping rules apply to classes and methods too. You can think of a method as a function, and a function does not know global variables per se. So now you've got several options how to make your header_main() method see the $websitename variable:

1. global keyword
Fastest, but ugliest approach: Use the "global" keyword to import the variable into the method's scope:



function header_main(){
global $websitename;
$str = '<div id="' . $this->style . '" class="header">' . $websitename . '</div>' ;

return $str ;

}


2. Use constants
Constants are visible in methods, can only contain simple values though (no objects etc.). That approach is IMO better because it makes your config variable immutable.



define("WEBSITE_NAME", "name");

function header_main(){
$str = '<div id="' . $this->style . '" class="header">' . WEBSITE_NAME . '</div>' ;

return $str ;

}


3. Pass the name as a parameter
You can pass the content to be inserted in the <div> as a parameter. Whether this makes sense or not depends on how often and where this method is called, thus how often you'd have to repeatedly pass the variable (<- hard to maintaion).




function header_main($content){
$str = '<div id="' . $this->style . '" class="header">' . $content . '</div>' ;

return $str ;

}

echo $yaks->header_main($websitename);


There are of course more ways to skin this cat... I only posted a few of them so you get an idea how to proceed on your own.

firepages
12-24-2003, 04:41 PM
hmmmm sorry to do this to you , but this may be a long post :D
and whilst I can `answer` your question in a line or 2 ... it won't really answer the question as such as there are so many other things to consider
Start with the first example (global $websitename) to see it working quickly , but consider the rest as well...

so, into the messy realm of globals ...

with your existing setup you have several options , the simplest is to globalise your variable ...



<?
function header_main(){
global $websitename;
$str = '<div id="' . $this->style . '" class="header">'.
$websitename .' header</div>' ;
return $str ;
}
?>


but using global variables is often a quick way to very messy code especially when used as above.

another option is to globalise your variables in ./config.php or set them as constants..

in ./config.php

$GLOBALS['websitename'] ='my site';
//or//
DEFINE( 'WEBSITENAME' , 'mysite' );

then just use them ...



<?
function header_main(){
$str = '<div id="' . $this->style . '" class="header">'.
$GLOBALS['websitename'] . ' or ' . WEBSITENAME .' header</div>' ;
return $str ;
}
?>



but even though we use a LOT of globals in PHP (_SESSION,_REQUEST etc) , it still adds some instability to our code as global values can be reset anywhere else in our code , perhaps by accident.

(If I use such schemes I generally make up my own globals array .. $GLOBALS['project_name']['websitename'] = 'mysite'; etc)

Constants are somewhat better , and $websitename would be the sort of variable I would consider defining as constant as it should indeed be constant ! , but other variables are exactly that , eg variable.

The next possiblity is to pass these variables to the constructor of our class as we did with new html_common( 'header' ) , eg htnl_common( 'header' , 'mysite' , 'etc' )

and this is ok to a point , but it soon gets messy , and variables passed to the constructor should really be important ones that alter or define the way the class works rather than sundry variables.

so next we have getters and setters.

in traditional OOP if you want to set the value of a class variable you use a setter ..



<?
//....in html_common
function set_websitename($websitename){
$this->websitename = $websitename ;
}
//.....

$yaks = new html_common();
$yaks->set_websitename( '$websitename ) ; //from ./config.php
?>


personally I think thats a waste of typing but thats personally , the following is generally frowned upon (but works a treat ;))



<?
function set_var( $name , $value ){
$this->$name = $value;
}
//......
$yaks = new html_common();
$yaks->set_variable( 'websitename' , 'my site' ) ;
?>


the main disadvantage of the above is that it alows you set a non-existant variable , or (until PHP5 protected variables) , overwrite an important existing one by 'accident' , also its much easier to validate datatypes when using a specific as opposed to a generic setter , there are many ways around that but thats another story !


ok lastly ... (and I am sure there are more options) we can look at object aggregation or composition , eg we have a config class ...




<?
class config{
function config(){
$this->websitename = 'my_site' ;
$this->bgcolor = 'blue' ;
$this->database_name = 'my_db' ;
//etc etc//
}
}
?>


to be fair its more of a structure than a class , it simply holds the stuff you would normally have in your config class.

so now we do this



<?
class config{
function config(){
$this->websitename = 'my_site ' ;
$this->bgcolor = 'blue' ;
$this->database_name = 'my_db' ;
//etc etc//
}
}

class html_common{
function html_common($style='' ){
/*reference our config class*/
$this->config = new config();
return true ;
}

function header_main(){
$str = '<div id="' . $this->style . '" class="header">'
.$this->config->websitename .'da header</div>' ;
return $str ;
}
}
$yaks = new html_common();
echo $yaks->header_main();
?>



hope I did not go too over the top here but a few ideas to play with anyway , some not 'good OOP' but 'good OOP' may not always be effective for an interpreted typeless language like PHP !

and I apoplogise if some of my terminology is not spot on , hopefully someone will point out any clangers there!

anyway happy holidays to all !

firepages
12-24-2003, 04:43 PM
lol looks like I got beaten to it ! , didnt see you there Mordred else I would have shut up :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum