The biggest advantage of the OOP vs procedural programming in PHP to my understanding is the sort of separation of the function names (sort of namespace).
So now when we have namespace since version 5.3, what do you think - For most cases (small to mid websites), when we need fast and again structured code, do the use of namespace + prodecural programming gains signifficant advantage over defining and writing in OOP.
Advantages:
structured
faster code/development
again we can define something like private functions within the namespace starting with "_" knowing that we don't need to use them
etc..
Code example:
namespace User;
function setPassword ($user_id) {
$pass = _generatePassword();
$sql = 'UPDATE `users` SET `password` = '.escape($pass).' WHERE `user_id` = '.escape($user_id);
$result = mysql_query($sql);
if (mysql_affected_rows() == 1) return $sql;
else return $sql;
}
function _generatePassword () {
$char = '0123456789abcdefghijklmnopqrstuvwxyz';
$str = '';
for ($i = 1; $i <= 6; $i++) {
$str .= $char[mt_rand(0, strlen($char))];
}
return $str;
}
Usage:
$user_id = 5;
User\setPassword($user_id);
I am asking for opinion. I know that it is just to the developers style, but maybe I am missing something.
PS. For most cases (small to mid websites) - I mean when you do websites for clients which are mostly 1 time development, and a little feature improvements in the long run.
You are thinking of OOP the wrong way. If you are trying to compare OOP with procedural namespaces merely as two different ways of organizing your code and function calls then certainly namespaces will seem more efficient.
The advantage of OOP isn't in organizing an object full of functions. That just treats OOP classes as big "utils" classes full of functions. The advantage of OOP isn't organizational. It is an entirely different way of building your programs that causes you to break your code into smaller, discreet entities. I use OOP in all of my PHP programs, even for small projects.
The advantage of OOP becomes most clear for me when doing any project that accesses a database (which is pretty well everything nowdays). I create small classes to model each database table and then access the information in these tables as objects. I have some base classes I use in all my projects that define how to map tables to objects so I don't retype or paste mysql commands any more. I just use the objects and they inherit all the needed functionality for inserting, updating and deleting from the database.
It sure is far more useful in code (especially if you use a PHP ide that has code completion) to see this in code:
echo "Hello, {$someDataObject->name}!";
Than this:
echo "Hello, " . $row['name'] . "!";
The difference might not be obvious right away. Both examples are a single line of code to print a table column. But the second example requires that I know the column names in my head. The first example has the column names embedded in the classes as properties. My code inspector knows all the properties so when I code it presents a list of all the properties as I type.
Maintaining the classes is easier than you think. Depending on the object framework you choose there are scripts to generate classes from tables and keep them up to date. And I find it FAR less error and bug prone to keep my object classes up to date myself than to have database changes break code because column names changed and then I have to update those column references in dozens of places. Yes, there is search and replace, but do you see the advantage of updating one file for your column change than updating every reference to $row['some_column']?
I hope this helps answer your question.
I think it is a valid question. With OOP style programming there tends to be a lot of overhead introduced as the problem space grows and the code base increases. It's fair to say that for small sized projects, there isn't any real difference between using OOP, functional or procedural, but this is not the case thereafter.
One of the advantages, although not the only one, touted by OOP programming doctrine is the benefit that namespacing gives you. Also, forcing the use of classes introduces another level of closer coupling and some dependancies in a lot of cases. What is proposed here is to write procedural code using only namespaces, which will allow reuse of functions in a much more natural way.
It's hard to be more concrete in the general case, and the examples presented in the original question don't reveal some of the potential benefit of avoiding the use of classes for the reasons mentioned.
Some of the arguments for not using an OOP style are more comparable with the arguments for and against functional programming languages. An interesting example to add here would be to look at the relatively new go language, written by the guys at google, which goes one step further and allows functions to be defined separate from structs or interfaces, using packages in their own namespace.
If the guys at google see some merit in the approach presented here, for my money, it doesn't seem such a bad thing to consider, and more than food for thought.
Related
I want to know when and why should I use class in php, I read at php.net that a class contains variables (we write var before them) and functions for these variables, so why not use regular functions ? I mean what does class do ?
and thank you.
Often suggested advantages to using an Object Oriented Programming (i.e.: OOP aka: class based) approach instead of traditional procedural programming are that OOP aids maintainability and provides a clearer separation of concerns (in the main due to the fact that an object is effectively a set of data and the operations that related to that data), although well constructed procedural code won't necessarily be significantly worse than a OOP approach.
Irrespective, I'd be tempted to take a look at the discussion over on: simple explanation PHP OOP vs Procedural? as I suspect this will answer many of your questions.
That said, it's worth bearing in mind that there's never a "one size fits all" approach, and sometimes a mix of both procedural and OOP is ideal.
Also, if you're a beginner to PHP (or programming in general) sometimes OOP (especially large frameworks like Zend) can initially seem overwhelming, but it's often worth the effort getting to know them. (It'll pay dividends down the line.)
As a final point, I'd personally say that OOP is generally more of a "systems thinking" approach, in that large systems generally break down (reasonably) naturally into objects. From the perspective of someone who's been using OOP for too many years to mention, I'd also say that it's at the very least worthy of some serious investigation. (The Wikipedia entry is as good a place to start as any.)
Using a class allows you to encapsulate and re-use code. Here's an example (PHP 5):
class car {
public $color;
public function __construct($color) {
$this->color = $color;
}
public function show_off() {
return 'This car is ' . $this->color;
}
}
// And now I can re-use the code elegantly:
$car_one = new car('blue');
$car_two = new car('red');
$car_thr = new car('yellow');
echo $car_one->show_off(); // This car is blue
echo $car_two->show_off(); // This car is red
echo $car_thr->show_off(); // This car is yellow
I must say that, like you—when I was still very green—I felt like OOP was a solution in search of a problem. But, after diving in and using it, eventually it clicked.
Objects, in their simplest form, are like containers of logic and data that you can pass around. This can be very advantageous.
And yet, I remember my mindset when I first started learning OOP. The above example would not click. The only way to appreciate it is to use it. Once you do, you'll be very glad you did.
Classes are a convenient way to group data and functionality. You could make a class to contain person information. Then, if you want a list of persons, you can make an array and put in it an instance of the class for each person. You fill the variables of the instances with data for the persons. This looks a lot like a two dimensional array (like an array of array of persondata), but it is more. You can build functions that are contained in the class that operate on the variables in the class. You could hide functions and variables from outside, so when you're building a framework you can distinguish between internal and external functionality.
And then, there is not even spoken about inheritance, which gives you even more possibilities.
All of this can be done in procedural code as well, but OOP (for Object Oriented Programming, which is programming using classes) gives you a whole new view on structuring your code.
Many big books have been written about this subject, so it is impossible to describe the exact details and possibilities in this post. All I can tell you is that you should give it a try, keep trying a while during the initial frustrations you'll encounter. And then, when someone else asks you this question, you'll advise them the same thing. :)
This question already has answers here:
Classes. What's the point?
(12 answers)
Closed 9 years ago.
if i have a collection of useful functions in a file called functions.php (easy enough)
what would be the advantage of OOP?
I want to learn it, but its pretty in depth so before I dive it, would be nice to know if there is an advantage. I can send variables to the functions just as easily as I can receive them.
example i have
functions del_some_string($x,$y)// made up function to delete y number of letters from $x
why would this be better as a OOP?
Depends on what the functions do, if you have some common data on which you do various operations to manipulate the same data you might want to model it in a class. On the other hand if all data you are working with has no relation with each other there is not really a benefit of using OOP.
For example the function you mentioned is more a utility function than a member of a class.
I've been using PHP for roughly 10 years now. I can't count how many times I've run across "functions.php" or "library.inc.php" or one of its many equivalents.
It's a bad idea. Don't do it. If you find yourselfs writing files like that, stop it. NOW.
It's not a matter of OOP vs functional programming. It's a matter of organising your code. Group your functions and variables properly and OOP will feel natural. If your functions do many things and don't lend themselves easily to being grouped, try to refactor them so they only do ONE thing at a time. You'll find that this also lets you strip a lot of redudancy out of your existing functions.
You can use OOP to encapsulate your code further: put your variables into objects and have the functions that operate on these variables either be property methods of those objects or interact with these objects as input. Avoid "global" and don't modify your function arguments routinely.
Your problems aren't the problems you think you have.
EDIT: As for your example: since strings aren't objects in PHP, you can't really put that function in a sensible class, so you'd probably want to put it into a utility module with other string functions and use it as you already do. Still, tearing apart your functions.php and turning it into a collection of atomic modules does wonders to your code's readability. You may find a file containing assorted functions readable because you are familiar with its contents, but another coder (and "you after three months of not using the code" IS another coder) will not.
EDIT2: Please understand that "OOP" doesn't magically make everything better. It's a tool that is supposed to help you writing better code. If you use OOP everywhere, you're probably doing it wrong (or writing for Java *cough*). If you use OOP without understanding things like structured code first, you won't get anything out of it, either.
It wouldn't. It's not a matter of better or worse. It's the paradigm that's important.
All computer programs aim to solve a problem. You can use Imperative Programming or you can use OOP (among others) to solve this problem. OOP will just change how you structure and organize your application, because it embraces concepts like encapsulation, polymorphism, and inheritance (to name some). These are not generally available in imperative programming, but that doesn't mean imperative is worse. It's just different.
If you are coding PHP, you can use either or. PHP is not a strictly object-oriented language. However, as of PHP5, there is an increased focus on OOP. New additions to the API are almost always Classes now (SPL, DateTime, Internationalization). If you want to use those, you definitely should look into OOP.
OOP goes much further then just calling functions.
Classes collect functions that operate on the same set of data or share the same goal. But another advantages of classes taking DRY to the next level. With functions, you can encapsulate some simple task so you don't have to repeat that over and over. With OOP, you can encapsulate more complex tasks so you won't have to repeat that.
If you tend to pass the same sort of data to several functions sequentially, you can think about using a class, and pass that data to the constructor and saving it in the class. That way, you can call the functions without having to pass that data each time.
You can instance of a PHP class and use it's all combined properties and methods. You can manipulate an object during the execution of the script, and state is saved.
class Myclass{
public $a, $b, $c;
public setA(){
$this->a = b;
}
public getA(){
return $this->a;
}
}
this is what you cant do with a function:
$x = new Myclass;
$x->setA();
print $this->getA();
you can't simulate the same functionality with a functions PHP. You run your functions one time, and since there is no instance, you have to hold these variables somewhere else. If you write a big aplication, this functions.php will be a big black hole. If you use seperated classes with it's functionality-aimed properties and methods, you can extend your PHP application as much as you want. If you don't use OOP, you can never setup a framework. but you will understand the importance of OOP, when you have to write something huge.
I'm fairly new to OOP in PHP, I've made a couple of basic scripts but nothing impressive. All I've really taken from it is that it would probably be easier just make a collection of functions and include them.
The structure of classes seems to just confuse what was otherwise a simple process. And in collating everything into a class it doesn't really add any functionality.
So I'm clearly missing something. Could someone explain what functionality is added by creating classes
Classes are a notion of object-oriented design (and programming and analysis, respectively), where they are used to encapsulate data and methods.
Other object-oriented programming techniques may include features such as
information hiding,
data abstraction,
encapsulation,
modularity,
polymorphism and
inheritance
From an article .. top-15-best-practices-for-writing-super-readable-code:
Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.
From http://java.sun.com/docs/books/tutorial/java/concepts/class.html:
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
Finally, a short youtube video about the differences between the procedural and object-oriented programming paradigm ...
While it may at first look simpler to just use a set of functions and include them, classes have their strong points. Classes can store variables and those variables are there "later."
Here's an edited example from php.net
<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name # \$$item_price for a total of: \$$item_total.";
?>
v.s:
<?php
class Item {
protected $name, $price, $qty, $total;
function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
function calculate($qty) {
$this->total = number_format(($this->price * $qty), 2);
}
public function __toString() {
return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
" at \$$this->price, for a total of: \$$this->total.";
}
}
$widget22 = new Item("Widget 22", 4.90);
$widget22->calculate(2);
echo $widget22;
?>
Another huge benefit is that you can make more of them. Say you want to calculate the price of another item and print it. Instead of having to duplicate all the fancy logic, you can just call new Item and be done.
A big advantage to OOP is code reuse. An example: Say you design a generic "Socket" class, which communicates with a server at a very low level. Then, I may come along and decide that I want to write an FTP class, which allows a user to download files while connected to an FTP server. I can "subclass" your Socket class and extend its functionality to support FTP, without rewriting your code.
Now, say John wants to write an HTTP class, to interact with HTTP servers. He, too, can subclass your Socket class to accomplish this, without rewriting the low level socket code.
Notice how in this example there was no duplication of socket code; both me and John shared it. Code duplication is bad because if there is an error in the duplicated code, the exact same bug may occur somewhere else in your code and you may not realize it.
More detailed information about classes can be found on Wikipedia.
Classes are a way to organize programs. Classes can be used to represent entities in the real world, or artifacts in our programming world, reducing the complexity of programs by allowing us to reason about them in terms of a higher granularity.
It is well-known in psychology that experts organize knowledge into "chunks" to allow them to reason more easily and quickly about their domain. Classes allow us to reason more easily and quickly about our programs.
In addition, classes allow us to group together the knowledge about an entity together with the methods/procedures/functions/operations that are naturally associated with that entity. Again, this provides a natural way to organize the information in our programs.
There are other advantages of classes, such as inheritance, but primarily classes are a cognitive way of organizing program structure to reduce the complexity.
Just a coupl months back I was posting similar questions about classes, I have been using PHP for a few years now and I really didn't see a need to use classes, they just complicated a simple process like you said, well I finally decided to jump in on the Class train and I am still learning but I am comfortable using them now and WOW I have a completely opposite way of thinking about them now, I think they are the best feature in PHP now!
I will admit they can be overkill for a small application but a large social network site like mine is far from small, it has hundreds of files and now that I am converting over to classes it is structured much better now and easiar to build, update, manage my code and other users could come in and understand my whole site a lot better now that it uses classes. Another great feature is you can break up all those functions you might have into seperate class files and use autoload() function to auto load the correct file only when the class is needed, this is great on a big project too. Classes make things more plug in play.
All I can say is it's kind of one of those things you need to dive into to see the REAL benefits of it.
I have thought exactly the same thing.
I have read a few books on OO-PHP, my favorite being PHP In Action.
Although when I read the books I thought "Hey, this is very useful and interesting information.", I have yet to use a significant amount of OO-PHP.
Simple needs like getting info from the server and JSON-ing it back really dont need OOP. Im sure it is "Best Practice", but for many people's needs it isn't practical. A few classes, like database connection, and similar data handling can be real time savers, but PHP is sometimes easier and quicker to be used only partially OO.
It would definitely be easy to code in procedural programming (that's what your simple process is called) if your website is small. But as your website grow, you will definitely need to sort things.
For example, you will need classes to act as templates for entities to the database. You might need classes to represent each page, and in a single file you might create multiple pages. Thus these are all advantages of OOP.
In another example you have like 40 over functions. You would want to group them together. Putting them in a class as static methods would definitely help. It'll clean things up so that in future when you come back to the same code, everything looks familiar to you.
I always thought the same thing until I started using classes--realizing that it is so much simpler and better.
You should create those functions that you're mentioning, but gather them all within a class. The functions can then within a class share the same variables, and therefore making it simpler when having to use the same functions multiple times.
The best example I can come up with now is connecting to a database.
Instead of having individual functions that connect, sends a query, fetching the results and closing the connection you could wrap all these functions within a class. This would allow you to communicate to the database multiple times using the same functions, without having to make loads of variables tailored for the specific use on the page.
If you're just writing procedural-style functions then slapping them together into a class you're not going to get many of the benefits of OOP. I think that the Open Closed Principle and the Dependency Inversion Principle describe some of the biggest benefits of OOP, which you wont get unless you intentionally design them into your code.
OOP isn't perfectly suited to everything, though. I think procedural programming is well suited to web development. It involves converting a (fairly) simple request into a bunch of HTML, which is a highly procedural task. If it's simpler to include a few functions, there's no point trying to shove an OOP shaped block into a procedurally shaped hole. However, I imagine that OOP would be the better option if the website was very complex.
All of the above poster have really good points. I would highly recommend the following books:
The OO Thought Process: http://www.amazon.com/Object-Oriented-Thought-Process-3rd/dp/0672330164/ref=sr_1_5?ie=UTF8&s=books&qid=1262547120&sr=8-5
PHP5 Objects, Patterns & Practice: http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_3?ie=UTF8&s=books&qid=1262546817&sr=8-3
OO Design Heuristics: http://www.amazon.com/Object-Oriented-Design-Heuristics-Arthur-Riel/dp/020163385X/ref=sr_1_1?ie=UTF8&s=books&qid=1262546869&sr=8-1
To manage complexity.
Edit: Maybe I shopuld elaborate a bit more.
Programs are complex entities and many ways have been proposed historically to tame their complexity.
Procedural programming, functions, structured programming, abstract data types and object-oriented programming are just models to help programmers manage the mental effort that is required to understand a program.
Object programming will not solve everything, and certainly for a small script it is overkill, but it works great for big applications or systems.
My original answer tries to summarize the full content of the humongous Code Complete book: do your best to manage complexity and make your programs understandable for you and your successors. It's great if you think that object programming will help you in this task, but it's even better that you question its convenience and try to find better ways.
In PHP, classes can, at the very least, save you a bunch of include statements. The lazy loading of the __autoload() function is very handy. Also, you can be confident that function names in different includes won't conflict.
To go beyond that, you can start to think of creating an API around a class. Functions which are needed only by other functions within the class can be marked private. And eventually, you should be able to ignore the actual code in your classes, and just think of them as API calls.
If I call Do::stuff($a, $b) I get this response.
And that's all you need to know. You can forget how it works "under the hood" inside the class.
And then, of course, there's classes with non-static functions. These can do various interesting things that normal functions can't.
Recently, I took it upon myself to try and learn OO programming. It has been about 3 months since I started, but I think I might be missing the point because I seem to prefer static methods (which seem 'easier' to me).
Example
Here is what a typical DB query looks like in my code.
$bindings = array(':name'=>$articleName);
Db::query('SELECT id, name, title, image, content FROM ' . CONFIG_MYSQL_TABLE_PREFIX . 'articles WHERE name = :name LIMIT 1', $bindings);
And here is how I resize/crop/cache images
$image = Img::thumbnail($imagePath, 200);
$imgHtml = '<img alt="' . $this->getTitle() . '" src="' . '' . $image['src'] . '" width="' . $image['width'] . '" height="' . $image['height'] . '" />';
Both of the static methods utilise a singleton pattern.. the first one creates one PDO object and the second one creates one ImageResize class I found on Google code.
Should these be 2 objects if I really wanted to call it object oriented programming? i.e.
$db = new Db();
$image = new Image($src, $width, $height);
For everytime I use them? I've read singletons are also a bad idea unless they're being used for logging to a file. But isn't a singleton good for one DB connection being opened when needed and closed only after it's been used and finished with?
My question is, am I still stuck in the procedural mindset, and if so, is what I'm doing considered bad practise? How can I immerse myself in the correct OO thought patterns?
Update
Thanks for the answers. I do find the original methods I'm doing are easier as I have to type less code and let the static methods worry about little implementation things.
I will look into another language to get a solid grasp of OO, which language though will be another question itself.
Well, imho PHP is a bad example for this because PHP is not object-oriented. Yes it has objects. Yes they support inheritance and all those OO principles. It supports objects. There's a difference.
I say this because PHP doesn't by default exist in a state between requests. Every single HTTP request will completely recreate a PHP environment from scratch (which is reasonably cheap), meaning there is no static data persisted between requests. You might say "what about session data?" (and maybe append an "a ha!') but that isn't persistent data in a PHP sense either. It's (typically) stored in the filesystem and keyed by a cookie the client sends.
Why do I mention these two things?
Because the "global" scope in not like the global scope in C, Java, C++ or these other languages because they tend to persist between requests. PHP is more like the CGI programming model from the 90s (which is no coincidence because that's where it originated).
So your objects aren't truly global: they are simply visible to all parts of the code servicing the current request.
To me, that's nowhere near as bad. In fact, I often find it quite acceptable. Sometimes it's every necessary (eg in a callback to preg_replace_callback if you want to send information back to the caller or pass state to the callback without doing eval()/create_function() hacks).
And the point about PHP not being object-oriented is because even in PHP 5 OO features are still somewhat "tacked on", meaning you could quite happily code away and code well in PHP without ever using them. This is different to, say, Java where you have to create a class even if all you do is write a bunch of static methods in it.
So if you want to learn OO, honestly I wouldn't do it in PHP. PHP is good for a lot of things but it's designed to have an HTTP request lifecycle (yes I know you can run it from the command line but that's not what the vast majority of users do) and it's quite good at the job it's designed for.
the best way to grasp object oriented programming is to think of objects passing messages to each other, not objects calling functions. i had this "eureka" moment when I learned Smalltalk.
there are principles that apply to OOP such as the "tell don't ask" principle and others. use your favourite search engine to look for those principles.
an abundance of static methods are, in my opinion, a sign of being stuck in a procedural mindset. sure there are scenarios where they really make sense but if your code has more static methods than instance methods i'd say you're not doing things the OO way.
you might find it easier to grasp the ideas more firmly in a language that supports OOP as the main paradigm... not that you can't do it in php or perl or whatever, it's just not as easy because there are few guardrails and encouragements
languages aside, it may also be the case that the kinds of things you are doing right now don't really require OOP; if so, don't sweat it, play with OOP on other things.
What OO helps with is managing state in an imperative environment.
To take the two examples you give, firstly Db::query, behind this I'm guessing is some database connection with it being a static method this means that everywhere in the software you're developing it's either:
Contending locks
Has mutli-threading issues
Reconnecing to the database for every transaction
You then might want to consider - what if I want to connect to two different databases?
By having Db as an object you're giving yourself more control over how the system may evolve.
Similarly with the thumbnail generation, should you want the system to cache thumbnails etc. by having an object deal with them it affords you better control over their life cycle and how they're shared.
By working with objects like this you can separate the concerns of your software and by doing so end up with pieces that you can re-use in different contexts.
As with anything it's a balance really only the context within which you work dictates the value of this kind of thing since you're new to OO I'd try for a bit (year or two) and see what actually seems to win you advantages when experience tells you that following such principles in your context is of little use then maybe stop following them just be wary when your context changes.
I struggle to imagine a worse way to learn about OO than Relational Databases in PHP. A few others have mentioned the problems with PHP. I'll point you to an article by our esteemed founder discussing why Objects and Relations don't mix:
Object-Relational Mapping is the Vietnam of Computer Science
You would do better to try something like GUI programming in Python. I recommend Python because it has good support for, but does not mandate OO, so you are less likely to see OO used in circumstances when it is inappropriate. I recommend GUI programming because GUI programming is almost impossible without OO techniques.
I don't use OO for the sake of using it. If I have to write a small program I prefer procedural approach. Using OO in smaller things can only complicate the problem or even if it doesn't it won't count for an advantage over procedural approach anyway.
But, if we are looking at a bigger problem involving many entities sure thing make a good class diagram and design to make realise and use the real power of OO. Use OO whenever wherever necessary; just don't apply OO in smaller problems for the sake of it.
Can someone please explain "re-usable structures" for me?
I was working on making some db objects in php, but was told I was using too much processing from the computer cause I made stuff to complicated with the below objects:
My DB objects:
$db = new Database;
$db->db_connect();
$post_content = new DbSelect;
$post_content->select('id', 'title', 'firstName', 'created', 'catName', 'tagName');
$post_content->from('content');
$post_content->join('inner');
$post_content->on('category','cat_id','id');
$post_content->where('id','1');
$post_content->order('created');
$db->db_close();
Normal PHP:
mysql_connect();
mysql_db_select();
$query = 'SELECT id, title, s_name, created, cat_name, tag_name
FROM content
JOIN INNER category, cat_id, id
WHERE id=1
ORDER created';
mysql_close();
So to reiterate my questions:
1. A quick explanation of re-usable structures?
2. why is the first method using objects "wrong"?
please note:
I'll be googling this as well as hoping for feedback
I know there a "tools" like Zend and other's that have plenty of db objects built into them, but I'm trying a DIY approach
Don't confuse object-oriented-programmed with "class-oriented" or "object-based" programming. They both, on the surface, can look like OOP but are not.
These are when you take structured code and wrap in a bunch of classes, but don't change the fundamentals of how it operates. When you program with objects in mind, but don't leverage any of the special conventions that OOP affords you (polymorphism, aggregation, encapsulation, etc). This is not OOP.
What you may have here is some of this type of code. It's a little hard to tell. Is the purpose of your DbSelect class to abstract away the raw SQL code, so that you can use connect to any database without having to rewrite your queries? (as many DBAL solutions are wont to do) Or are you doing it "just because" in an effort to look like you've achieved OOP because you turned a basic SQL query into a chain of method calls? If the latter is closer to your motivation for creating this set of classes, you probably need to think about why you're making these classes and objects in the first place.
I should note that, from what I can tell by your simple snippet, you actually have not gained anything here in the way of re-usability. Now, your design may include code that gives flexibility where I cannot see it, but kind of suspect that it isn't there. The procedural/structured snippet is really no more or less reusable than your proposed class-based one.
Whomever you were talking to has a point - developing a complex (or even simple) OOP solution can definitely have many benefits - but to do so without regard to the cost of those benefits (and there's always a cost) is foolish at best, and hazardous at worst.
I'm not sure where to start on this one. Object Oriented design is not a trivial subject, and there are many ways it can go wrong.
Essentially, you want to try to make logical indepedent objects in your application such that you can swap them out for other modules with the same interface, or reuse them in future projects. In your database example, look at PEAR::MDB2. PEAR::MDB2 abstracts the database drivers away from your application so that you don't need to worry about which specific database you're using. Today, you might be using MySQL to run your site. Tomorrow, you might switch to Postgresql. Ideally, if you use a proper OO design, you shoudn't need to change any of your code to make it work. You only need to swap out the database layer for another. (Pear::MDB2 makes this as simple as changing your db connect string)
May I suggest reading Code Complete by Steve McConnell. There's a whole chapter on Classes. While the examples are primarily C++, the concepts can be applied to any programming language, including PHP.
It seems that your solution involves more typing to achieve the same thing as the "normal" way. The string SQL would be more efficient than allocating memory for your object.
You should check out the Active Record pattern if you want to create a data abstraction layer with more features than just a select.
If you are using DbSelect objects to build queries from complicated Forms, then you are doing the right thing.
Query Object pattern