March 30, 200818 yr I've started to work with now. But I still have a little difficulty with classes. I have a few questions... 1. When exactly would classes be more useful than say just normal functions? 2. What are the best programming practices for classes? 3. What would be a good PHP class for me to study? Wordpress database class? *Classes referring to PHP OOP
March 30, 200818 yr Hi Daniel - I was asking exactly these questions a year ago until I just bit the bullet and started forcing myself to write in classes. The main difference between is a class and normal function is that a class has memory for each of it's instances. Secondly, compartmentalisation helps here (meaning everything is tied together as part of the class namespace, eg ClassName::MethodName()) Classes, from my experience, are just plain better for everything apart from the tiny stuff (eg helper functions which clean a string) ... once you have written the class, and if you write it well, everything will just fall into place. Here is an example of getting the results from two tables, and setting a value from one row into another row from the other table: Serialised (just functions) : // imagine we have a function called dbget( String table ); $table1 = dbget( 'firstTable' ); $table2 = dbget( 'secondTable' ); $row1 = $table1[ '42' ][ 'afield' ]; // swapping this $row2 = $table2[ '17' ][ 'anotherfield' ]; // with this, and vice versa // and a dbwrite( String table, Array where, Array data ) function $write = dbwrite( 'firstTable', array( "id"=>42 ), array( "afield"=>$row2 ) ); $write2= dbwrite( 'secondTable', array( "id"=>17 ), array( "anotherfield"=>$row1 ) ); Because there are some nice helper functions I have imagined there, it took 6 lines of code. Now with a class (using this class) $table1 = new DBEntity( 'table1', 42 ); $table2 = new DBEntity( 'table2', 17 ); $hold = $table1->afield; $table1->afield = $table2->anotherfield; $table2->anotherfield = $hold; $table1->Save(); $table2->Save(); Now it is 7 lines of code - but look how much simpler it is? I have only written the table names once, the words involved are simpler (IMO ->save() is easier than dbwrite( table, where, data )) Finally - don't study classes you boring oaf! Write some of your own! You will quickly learn what works, what went wrong, and without too much luck you won't fall into a pit of despair
March 30, 200818 yr Author Haha love your last comment php_penguin. I've written some of my own... it just seems so awkward right now. But I'm going to rewrite the database one that I did and see how it goes. Thanks for the comments
March 31, 200818 yr When you are used to inline functions, classes do seem a bit weird. But if you practice, soon you will think of everything as a set of objects, with values and functions and it will just seem to make so much more sense this way, and of course you'll end up with tonnes more reusable code.
Create an account or sign in to comment