[PHP] PHP5 OOP: Abstract classes, multiple inheritance and constructors
Example/working code here: https://gist.github.com/mhulse/5833826 Couple questions: 1. Is there anything wrong with the way I'm using the abstract class? If so, how could I improve the logic/setup? 2. Is there a way for me to pass $foo to the parent class, from the child, without having to ferry that variable through the abstract class? In other words, is there such a thing as: parent::parent::__construct($foo); ... I want to have my abstract class constructor do things, yet I'd like to avoid having to repeat myself for when it comes to passing constructor arguments from the child. Any tips would be appreciated. Sorry if silly questions. Thanks! Micky -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 oop question...
Andrei wrote: Hi list, I have a class which I use to parse simple bbcode inside some comments. I noticed on PHP5 that scope of preg_replace function is changed when function is called inside a class. To the point: [CODE] class PHS_editor { ... function parse_content( $str = null ) { $from_arr = array( @\[B\](.*?)\[\/[EMAIL PROTECTED], @\[U\](.*?)\[\/[EMAIL PROTECTED], @\[I\](.*?)\[\/[EMAIL PROTECTED], @\[URL=([^\]]*)\]([^\[]*?)\[\/[EMAIL PROTECTED], @\[IMG=([^\]]*)[EMAIL PROTECTED], @\[QUOTE=([^\]]*)\]([^\[]*?)\[\/[EMAIL PROTECTED] ); $to_arr = array( 'b\1/b', 'u\1/u', 'i\1/i', 'a href=\1 target=_blank\2/a', 'img src=\'.stripslashes( \*$this-get_image_location*( '\\1' ) ).'\ border=\0\', 'table width=\98%\ align=\center\ cellpadding=\1\ cellspacing=\0\ border=\0\ class=\form_type\. tr. td class=\maintext\'.stripslashes( \*$this-remove_mytags*( '\\2' ) ).'/td. /tr. /table' ); if( is_null( $str ) ) $str = $this-editor_content; return preg_replace( $from_arr, $to_arr, str_replace( , nbsp;, nl2br( $str ) ) ); } ... } [/CODE] When it gets to parse [IMG] tags I get Fatal error: Using $this when not in object context in So it seems they changed the scope for preg_replace callback functions. As this function is called inside the method shouldn't it have the scope of the class? Is there a workaround for this? I cannot declare a function get_image_location which will staticly call the method bcuz I use variables from instanced class. How are you trying to use this class? It sounds like you're trying to use the method statically. When a method is called statically it does not have a $this. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 oop question...
Stut wrote: Andrei wrote: Hi list, I have a class which I use to parse simple bbcode inside some comments. I noticed on PHP5 that scope of preg_replace function is changed when function is called inside a class. To the point: [CODE] class PHS_editor { ... function parse_content( $str = null ) { $from_arr = array( @\[B\](.*?)\[\/[EMAIL PROTECTED], @\[U\](.*?)\[\/[EMAIL PROTECTED], @\[I\](.*?)\[\/[EMAIL PROTECTED], @\[URL=([^\]]*)\]([^\[]*?)\[\/[EMAIL PROTECTED], @\[IMG=([^\]]*)[EMAIL PROTECTED], @\[QUOTE=([^\]]*)\]([^\[]*?)\[\/[EMAIL PROTECTED] ); $to_arr = array( 'b\1/b', 'u\1/u', 'i\1/i', 'a href=\1 target=_blank\2/a', 'img src=\'.stripslashes( \*$this-get_image_location*( '\\1' ) ).'\ border=\0\', 'table width=\98%\ align=\center\ cellpadding=\1\ cellspacing=\0\ border=\0\ class=\form_type\. tr. td class=\maintext\'.stripslashes( \*$this-remove_mytags*( '\\2' ) ).'/td. /tr. /table' ); if( is_null( $str ) ) $str = $this-editor_content; return preg_replace( $from_arr, $to_arr, str_replace( , nbsp;, nl2br( $str ) ) ); } ... } [/CODE] When it gets to parse [IMG] tags I get Fatal error: Using $this when not in object context in So it seems they changed the scope for preg_replace callback functions. As this function is called inside the method shouldn't it have the scope of the class? Is there a workaround for this? I cannot declare a function get_image_location which will staticly call the method bcuz I use variables from instanced class. How are you trying to use this class? It sounds like you're trying to use the method statically. When a method is called statically it does not have a $this. -Stut Yes, method was called staticly. Strange tho in php 4 it worked. Thnx for enlighting me with this. Andy -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] php5 oop question
Ok, I have seen many different examples of OOP, but nothing quite like this. Someone was showing me syntax for Ruby the other day, and it got me thinking, wouldn't it be neat to imitate ruby, or be it a little more generic, dot notation for OOP ways of calling methods like Java, javascript, ruby and others. So I came up with this. Seems to work in PHP5, but chokes in PHP4. I would like input on this setup for calling methods. plaintext?php class myString { private $value = ''; function __construct() { } function in($str=null) { if ( is_null($str) ) { echo A string wasn't given.; exit; } $this-value = $str; $this-setProperties(); return $this; } function out() { echo $this-value; } function get() { return $this-value; } function append($a) { $this-value = $this-value.$a; $this-setProperties(); return $this; } function prepend($a) { $this-value = $a.$this-value; $this-setProperties(); return $this; } function regex_replace($from, $to) { $this-value = preg_replace(!{$from}!, $to, $this-value); $this-setProperties(); return $this; } function setProperties() { $this-str_length = strlen($this-value); return $this; } function length() { return $this-str_length; } } $str = new myString; echo $str-in(Starting String!)-prepend(Second String!)-regex_replace(' ', '_')-get(); echo $str-length(); $str-in(A new string)-out(); ? Has anybody else seen this style of syntax? Have they used this style of syntax? If so, what is your opinion of this style? TIA Jim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? http://5ive.uwc.ac.za/index.php?module=blogaction=viewsinglepostid=init_8059_1163957717userid=5729061010 I don't think that its really useful for anything, except maybe creating overly complex SQL queries. --Paul All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/uwc2006/content/mail_disclaimer/index.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
Paul Scott wrote: On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? http://5ive.uwc.ac.za/index.php?module=blogaction=viewsinglepostid=init_8059_1163957717userid=5729061010 I don't think that its really useful for anything, except maybe creating overly complex SQL queries. --Paul All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/uwc2006/content/mail_disclaimer/index.htm What about using it for math? Here is the other example that I worked up. plaintext?php class Math { function __construct() { } function in($num=null) { if ( is_null($num) ) { echo A number was not given on initialization.; exit; } $this-value = $num; return $this; } function out() { echo $this-value; } function get() { return $this-value; } function add($n) { $this-value += $n; return $this; } function subtract($n) { $this-value -= $n; return $this; } function multiply($n) { $this-value *= $n; return $this; } function divide($n) { $this-value /= $n; return $this; } } $mObj = new Math(); $mObj-in(10)-add(90)-divide(5.3)-multiply(10)-out(); ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
Paul Scott wrote: On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? http://5ive.uwc.ac.za/index.php?module=blogaction=viewsinglepostid=init_8059_1163957717userid=5729061010 I don't think that its really useful for anything, except maybe creating overly complex SQL queries. --Paul All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/uwc2006/content/mail_disclaimer/index.htm well, I guess the better question is, is why when I talk others about oop, they say that this style of syntax is OOP, and anything else is not. be it dot notation or the pointers (-) in php. I heard it called messaging at one point in the past. the passing up of information in the tree. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
# [EMAIL PROTECTED] / 2007-04-11 23:36:56 -0700: Paul Scott wrote: On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? I don't think that its really useful for anything, except maybe creating overly complex SQL queries. What about using it for math? class Math { function __construct() { } function in($num=null) { if ( is_null($num) ) { echo A number was not given on initialization.; exit; } $this-value = $num; return $this; } function out() { echo $this-value; } function get() { return $this-value; } function add($n) { $this-value += $n; return $this; } function subtract($n) { $this-value -= $n; return $this; } function multiply($n) { $this-value *= $n; return $this; } function divide($n) { $this-value /= $n; return $this; } } $mObj = new Math(); $mObj-in(10)-add(90)-divide(5.3)-multiply(10)-out(); The class really represents a number, not Math, that's too abstract (pun intended) for an instantiable class. Besides, you're mixing together two responsibilities, Math should really be called Number, it should be immutable, and you'll spare someone from a terrible debugging session caused by someone doing $math = new math; $ten = $math-in(10); $five = $ten-subtract(5); $fifty = $ten-add(40); ($fifty is actually 45, because $ten is 5 after the subtract() call) -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
# [EMAIL PROTECTED] / 2007-04-11 23:44:16 -0700: Paul Scott wrote: On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? http://5ive.uwc.ac.za/index.php?module=blogaction=viewsinglepostid=init_8059_1163957717userid=5729061010 I don't think that its really useful for anything, except maybe creating overly complex SQL queries. well, I guess the better question is, is why when I talk others about oop, they say that this style of syntax is OOP, and anything else is not. *What* style of syntax? Syntax is grammar, a set of rules, the visible part of a programming language, something you either follow or you get a parse error. To which grammar are you referring? be it dot notation or the pointers (-) in php. Having primitive types, including literals, behave like instances of a class helps writing object-oriented code, because you don't have to special case. It's not required, however. You can write o-o code in today's PHP, it just won't be purely objective. I heard it called messaging at one point in the past. the passing up of information in the tree. Different people use different metaphors. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
I've seen it referred to as a Fluent Interface. I built one just to see how hard it was, using a standard problem: data validation. The results were promising. I combined it with an object designed to work as a factory for an internally stored decorator pattern. Class Input was the factory, with a private property to hold the decorator object in question and a method for adding Decorators to the stored object based on a simple switch command. Class Checker was the root class of the decorator pattern, doing nothing but returning TRUE on its check() method. Decorator Classes for Checker included IntegerChecker, NumericChecker, NonEmptyChecker, RegExpChecker, EmailChecker, etc. etc. All of which extended Checker, have their own custom check() method and a property to store the Decorator object which they wrap. Each Checker applies its check(X) method first, then passing a successful request along to the Decorator object they store. Input has a check() method that just passes the request along to its stored Decorator object. By using the Fluent style of interface, the end result was ?php $_input = new Input(); $_input-addCheck('Integer') -addCheck('Range',3,9) -addCheck('NonEmpty'); echo ($input-check('4.734'))? 'Pass': 'Fail'; ? It returns 'Fail'. Why? It passed the NonEmpty test, passed the Range test, failed the Integer test. print_r of $input object: Input Object ( [_checker:private] = NonEmptyChecker Object ( [_checker:private] = RangeChecker Object ( [_checker:private] = IntegerChecker Object ( [_checker:private] = Checker Object ( ) ) [_min] = 3 [_max] = 9 ) ) ) Validation works from the outside in, responses are passed from the inside out, so on first failure, the validation process bails. I loop through an array of prepared Input objects for validating the supplied Post values from a form and get back a simple pass/fail response for each. A bit of work to set up initially, but once the system is built, it's pretty elegant. Tim Stiles Icomex.com, DallasPHP.org On Apr 12, 2007, at 1:29 AM, Paul Scott wrote: On Wed, 2007-04-11 at 23:22 -0700, Jim Lucas wrote: Has anybody else seen this style of syntax? http://5ive.uwc.ac.za/index.php? module=blogaction=viewsinglepostid=init_8059_1163957717userid=57290 61010 I don't think that its really useful for anything, except maybe creating overly complex SQL queries. --Paul All Email originating from UWC is covered by disclaimer http:// www.uwc.ac.za/portal/uwc2006/content/mail_disclaimer/index.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php Tim Stiles, WatchMaker, Icomex.com
Re: [PHP] php5 oop question
I suppose I should have summarized what I learned from that experiment, putting myself more squarely on topic: Simply put, a Fluent interface let me move from $_input-addCheck('Integer'); $_input-addCheck('Range',3,9); $_input-addCheck('NonEmpty'); to $_input-addCheck('Integer') -addCheck('Range',3,9) -addCheck('NonEmpty'); with almost no effort. Not a huge timesaver, but I kept it in because I find the necessary code that I'll use repeatedly to be less cluttered and easier to read. Less experienced developers who will have to work with my code felt the same way. It just feels like less labor. And as a solution, it suited this problem well, mirroring how most people mentally approached the issue - making it easier for them to understand the code at a glance. I elaborated on that problem because it was specifically the nature of the problem that led me to Fluent interfaces as being part of the solution. I needed to set up a complex configuration within the object, but needed only a very simple response from it. Like others pointed out, a SQL query is a very simple thing, but building one may involve many seemingly simple steps that occur in no prescribed particular order, and you don't need the result until the configuration is complete. Fluent interfaces can hide complexity. 1) Fluent interfaces seem to work best when most of your methods alter the internal characteristics of an object. Setting properties, not Getting them. You can't really use a fluent interface when you actually NEED a specific response from your method: they work by returning a reference to the object itself instead of returning a value - that way, the response they deliver is set up and ready to receive a new, unrelated method call. You can combine the fluent with the conventional, but then you have to remember that any non- fluent call must occur last in a string of requests. I could have easily written: $test = $_input-addCheck('Integer') -addCheck('Range',3,9) -addCheck('NonEmpty') -check('4.97'); if($test)? ... but I found it more legible to stay conventional when using non- fluent methods. Basically, if you have configuration processes that often need to be called sequentially, but not always in the same sequence, Fluent interfaces can smooth the rough edges. 2) Fluent interfaces probably work better with thrown exceptions than they do with error notices. If you generate a non-fatal error in the middle of a string of fluent method calls, how do you cope with it? Return the object anyway and let the next method continue? Not return the object and get a new error because your error message can't accept a method call? Bail out at the point of error within your method instead of pointing where the error was caused? Exceptions move the error handling outside of the predicted flow of the fluent interface, making them easier to deal with. Your errors represent what actually went wrong instead of being a side-effect or symptom of something that went wrong earlier in the process. To sum up, Fluent interfaces seem to be a great solution when combined with a certain set of well-defined problems and practices. PHP5 makes them even more useful. They save some keystrokes, they can improve code legibility, they can make PHP code more intuitive for people who weren't the ones who created it. I don't think they make code execution any faster (or slower, for that matter). It's worth knowing about them, but they probably shouldn't change your day to day practices. As with most techniques, it becomes a matter of knowing when to apply this particular tool. Tim Stiles, WatchMaker, Icomex.com DallasPHP.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
nice write up. :-) Tim Stiles wrote: I suppose I should have summarized what I learned from that experiment, putting myself more squarely on topic: Simply put, a Fluent interface let me move from /snip -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
a) I don't see how the part about the dot notation has anything to do with the class presetned b) I don't see any benefit to the class presented c) Trying to follow the chain of - operators and method calls just gave me a headache. Other than that, it's really nifty. :-v On Thu, April 12, 2007 1:22 am, Jim Lucas wrote: Ok, I have seen many different examples of OOP, but nothing quite like this. Someone was showing me syntax for Ruby the other day, and it got me thinking, wouldn't it be neat to imitate ruby, or be it a little more generic, dot notation for OOP ways of calling methods like Java, javascript, ruby and others. So I came up with this. Seems to work in PHP5, but chokes in PHP4. I would like input on this setup for calling methods. plaintext?php class myString { private $value = ''; function __construct() { } function in($str=null) { if ( is_null($str) ) { echo A string wasn't given.; exit; } $this-value = $str; $this-setProperties(); return $this; } function out() { echo $this-value; } function get() { return $this-value; } function append($a) { $this-value = $this-value.$a; $this-setProperties(); return $this; } function prepend($a) { $this-value = $a.$this-value; $this-setProperties(); return $this; } function regex_replace($from, $to) { $this-value = preg_replace(!{$from}!, $to, $this-value); $this-setProperties(); return $this; } function setProperties() { $this-str_length = strlen($this-value); return $this; } function length() { return $this-str_length; } } $str = new myString; echo $str-in(Starting String!)-prepend(Second String!)-regex_replace(' ', '_')-get(); echo $str-length(); $str-in(A new string)-out(); ? Has anybody else seen this style of syntax? Have they used this style of syntax? If so, what is your opinion of this style? TIA Jim -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- Some people have a gift link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php5 oop question
I have never heard that described as a fluent interface before, but you'd probably like jQuery. :-) It's a javascript library that uses much the same concept, although it refers to it as function chaining. It also operates on multiple objects simultaneously, which is even niftier. On Thursday 12 April 2007 12:37 pm, Tim Stiles wrote: I suppose I should have summarized what I learned from that experiment, putting myself more squarely on topic: Simply put, a Fluent interface let me move from $_input-addCheck('Integer'); $_input-addCheck('Range',3,9); $_input-addCheck('NonEmpty'); to $_input-addCheck('Integer') -addCheck('Range',3,9) -addCheck('NonEmpty'); with almost no effort. Not a huge timesaver, but I kept it in because I find the necessary code that I'll use repeatedly to be less cluttered and easier to read. Less experienced developers who will have to work with my code felt the same way. It just feels like less labor. And as a solution, it suited this problem well, mirroring how most people mentally approached the issue - making it easier for them to understand the code at a glance. I elaborated on that problem because it was specifically the nature of the problem that led me to Fluent interfaces as being part of the solution. I needed to set up a complex configuration within the object, but needed only a very simple response from it. Like others pointed out, a SQL query is a very simple thing, but building one may involve many seemingly simple steps that occur in no prescribed particular order, and you don't need the result until the configuration is complete. Fluent interfaces can hide complexity. 1) Fluent interfaces seem to work best when most of your methods alter the internal characteristics of an object. Setting properties, not Getting them. You can't really use a fluent interface when you actually NEED a specific response from your method: they work by returning a reference to the object itself instead of returning a value - that way, the response they deliver is set up and ready to receive a new, unrelated method call. You can combine the fluent with the conventional, but then you have to remember that any non- fluent call must occur last in a string of requests. I could have easily written: $test = $_input-addCheck('Integer') -addCheck('Range',3,9) -addCheck('NonEmpty') -check('4.97'); if($test)? ... but I found it more legible to stay conventional when using non- fluent methods. Basically, if you have configuration processes that often need to be called sequentially, but not always in the same sequence, Fluent interfaces can smooth the rough edges. 2) Fluent interfaces probably work better with thrown exceptions than they do with error notices. If you generate a non-fatal error in the middle of a string of fluent method calls, how do you cope with it? Return the object anyway and let the next method continue? Not return the object and get a new error because your error message can't accept a method call? Bail out at the point of error within your method instead of pointing where the error was caused? Exceptions move the error handling outside of the predicted flow of the fluent interface, making them easier to deal with. Your errors represent what actually went wrong instead of being a side-effect or symptom of something that went wrong earlier in the process. To sum up, Fluent interfaces seem to be a great solution when combined with a certain set of well-defined problems and practices. PHP5 makes them even more useful. They save some keystrokes, they can improve code legibility, they can make PHP code more intuitive for people who weren't the ones who created it. I don't think they make code execution any faster (or slower, for that matter). It's worth knowing about them, but they probably shouldn't change your day to day practices. As with most techniques, it becomes a matter of knowing when to apply this particular tool. Tim Stiles, WatchMaker, Icomex.com DallasPHP.org -- Larry Garfield AIM: LOLG42 [EMAIL PROTECTED] ICQ: 6817012 If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it. -- Thomas Jefferson -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] PHP5 OOP how do I get the list of all classes dynamically?
I have a class class XMLRule { ... } And many of these: class is_username extends XMLRule { } class is_device extends XMLRule { } Is there a way in PHP5 to get a list of all the 'extends' classes I have 'defined' in my .php file? I'm sure this is a long shot, but thought maybe through the Reflection class or something? I really don't want to manually maintain an array if I don't have to. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] PHP5 OOP
Any recommendations on the best PHP5 OOP book to get? I have Advanced PHP Programming by George Schlossnagle. It's turning out to be a great book, but I'd like to read more on PHP5 OOP. The first chapter recommends two books, but both deal with OOP from the perspective of C++, C#, and Perl. Thanks, Ed
Re: [PHP] PHP5 OOP
On Fri, 10 Sep 2004 15:09:57 -0700, Ed Lazor [EMAIL PROTECTED] wrote: Any recommendations on the best PHP5 OOP book to get? I have Advanced PHP Programming by George Schlossnagle. It's turning out to be a great book, but I'd like to read more on PHP5 OOP. The first chapter recommends two books, but both deal with OOP from the perspective of C++, C#, and Perl. Do not bother to get PHP5 and MySQL Bible unless you're a complete PHP beginner. The one OO chapter is not much more than is in the PHP manual. I got it and wish I hadn't. Overall it's long-winded and the humor is dry. Tons of useless chatter in between the information you really want. -- Greg Donald http://destiney.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 OOP
Greg Donald wrote: On Fri, 10 Sep 2004 15:09:57 -0700, Ed Lazor [EMAIL PROTECTED] wrote: Any recommendations on the best PHP5 OOP book to get? I have Advanced PHP Programming by George Schlossnagle. It's turning out to be a great book, but I'd like to read more on PHP5 OOP. The first chapter recommends two books, but both deal with OOP from the perspective of C++, C#, and Perl. Do not bother to get PHP5 and MySQL Bible unless you're a complete PHP beginner. The one OO chapter is not much more than is in the PHP manual. I got it and wish I hadn't. Overall it's long-winded and the humor is dry. Tons of useless chatter in between the information you really want. Honestly, if you want to learn OOP in php5, the best way to do it is to get an IDE that contains a PHP 5 step-through debugger such as Zend IDE and try out the stuff you see in the link from the php.net home page regarding Zend Engine 2. It is very similar to java/c# and perl in terms of the similarity to those features (exceptions, try/catch, PPP are all from those languages). The big changes are the new xml extensions and their derivatives like simplexml, dom, soap. Learning the DOM extension and simplexml is very difficult to do without some kind of prior knowledge of DOM, but you'll learn more from sites like w3cschools.com than you will from a book. In addition, ReflectionClass is your friend, as in: ?php $a = new ReflectionClass('DOMDOcument'); var_dump($a-getMethods()); // or even $a = new ReflectionClass('ReflectionClass'); var_dump($a-getMethods()); ? I would recommend starting with the big red Beginning PHP4 and then simply using trial and error to learn the differences with PHP5, it's not all that different from php4 in the basics, it is a question of how you use it. Greg -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 OOP
On Fri, 10 Sep 2004 15:09:57 -0700, Ed Lazor [EMAIL PROTECTED] wrote: Any recommendations on the best PHP5 OOP book to get? I have Advanced PHP Programming by George Schlossnagle. It's turning out to be a great book, but I'd like to read more on PHP5 OOP. The first chapter recommends two books, but both deal with OOP from the perspective of C++, C#, and Perl. The language doesn't matter. If you're learning OOP, you need to learn the concepts first, which can then be applied to any language. I have the following book which I'd highly recommend: http://www.amazon.com/exec/obidos/tg/detail/-/0672318539/103-7282797-1853467?v=glance -- ---John Holmes... Amazon Wishlist: www.amazon.com/o/registry/3BEXC84AB3A5E/ php|architect: The Magazine for PHP Professionals www.phparch.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] PHP5 OOP
Thanks everyone for the recommendations =) -Original Message- On Fri, 10 Sep 2004 15:09:57 -0700, Ed Lazor [EMAIL PROTECTED] wrote: Any recommendations on the best PHP5 OOP book to get? I have Advanced PHP Programming by George Schlossnagle. It's turning out to be a great book, but I'd like to read more on PHP5 OOP. The first chapter recommends two books, but both deal with OOP from the perspective of C++, C#, and Perl. The language doesn't matter. If you're learning OOP, you need to learn the concepts first, which can then be applied to any language. I have the following book which I'd highly recommend: http://www.amazon.com/exec/obidos/tg/detail/-/0672318539/103-7282797- 1853467?v=glance -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] PHP5 OOP
Hello, I'm trying to get the hang of OOP here but can't quite figure out how to relate these classes. I've got one for the main project, one for the database, and one for a user. Somehow I need to get the user access to the database, without cumbersome constructor calls involving a copy of the instance of the class itself. // main project class class gfusion { protected static $db; function __construct() { $this-db = new db; } } // database class class db { private $link; private $query; private $result; ... function query($query); function fetch_row(); function fetch_rows(); ... } // user class class user { private $id; private $group_id; private $login; private $password; /* Somehow I need to get the db class instance here. */ function __construct($id = false) { if (is_numeric($id)) { print_r($this); $this-db-query('SELECT * FROM user WHERE id = ' . $id); $user_info = $this-db-get_row(); $this-id = $user_info['id']; $this-group_id = $user_info['group_id']; $this-login = $user_info['login']; $this-password = $user_info['password']; } } ... } I tried extending the user class from the project class, but that didn't work, because the $db var was empty. I tried changing it to static, but it didn't inherit the $db variable for some reason. So, how can I make this work, so I can write a bunch of classes that can blindly use $this-db or something similar without having to worry about setting it in the constructor? I thought about setting it as a global, but that didn't seem very... OOP. -- Joel Kitching http://midgardmanga.keenspace.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 OOP
Hello, I'm trying to get the hang of OOP here but can't quite figure out how to relate these classes. I've got one for the main project, one for the database, and one for a user. Somehow I need to get the user access to the database, without cumbersome constructor calls involving a copy of the instance of the class itself. snip class I tried extending the user class from the project class, but that didn't work, because the $db var was empty. I tried changing it to static, but it didn't inherit the $db variable for some reason. So, how can I make this work, so I can write a bunch of classes that can blindly use $this-db or something similar without having to worry about setting it in the constructor? I thought about setting it as a global, but that didn't seem very... OOP. -- Joel Kitching http://midgardmanga.keenspace.com/ This is a great class to learn how OO works in PHP5. class DB_Mysql { protected $user; // Database username protected $pass; // Database password protected $dbhost;// Database host protected $dbname;// Database name protected $dbh; // Database handle public function __construct($user, $pass, $dbhost, $dbname) { $this-user = $user; $this-pass = $pass; $this-dbhost = $dbhost; $this-dbname = $dbname; } protected function connect() { $this-dbh = @mysql_connect($this-dbhost, $this-user, this-pass); if (!is_resource($this-dbh)) { throw new Exception(Cannot connect to the database); } if (!mysql_select_db($this-dbname, $this-dbh)) { throw new Exception(No such database by that name); } } public function execute($query) { if (!$this-dbh) { $this-connect(); } $ret = mysql_query($query, $this-dbh); if (!$ret) { throw new Exception(There is an issue with the query string); } elseif (!is_resource($ret)) { return TRUE; } else { $stmt = new DB_MysqlStatement($this-dbh, $query); $stmt-result = $ret; return $stmt; } } } class DB_MysqlStatement { public $result; public $query; protected $dbh; public function __contruct($dbh, $query) { $this-query = $query; $this-dbh = $dbh; if (!is_resource($dbh)) { throw new Exception(Cannot connect to the database); } } public function fetch_row() { if (!$this-result) { throw new Exception(There is an issue with the query string); } return mysql_fetch_row($this-query); } public function fetch_assoc() { return mysql_fetch_assoc($this-result); } public function fetchall_assoc() { $retval = array(); while ($row = $this-fetch_assoc()) { $retval[] = $row; } return $retval; } } Then call it like: $dbhObj = new DB_Mysql(user,passwd,localhost,DBname); $query = SELECT * FROM user WHERE id = ' . $id; $result = $dbhObj-execute($query); while ($row = $result-fetch_assoc()) { //do stuff with $row array } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 OOP
From: Joel Kitching [EMAIL PROTECTED] Hello, I'm trying to get the hang of OOP here but can't quite figure out how to relate these classes. I've got one for the main project, one for the database, and one for a user. Somehow I need to get the user access to the database, without cumbersome constructor calls involving a copy of the instance of the class itself. // main project class class gfusion { protected static $db; function __construct() { $this-db = new db; } } // database class class db { private $link; private $query; private $result; ... function query($query); function fetch_row(); function fetch_rows(); ... } // user class class user { private $id; private $group_id; private $login; private $password; /* Somehow I need to get the db class instance here. */ function __construct($id = false) { if (is_numeric($id)) { print_r($this); $this-db-query('SELECT * FROM user WHERE id = ' . $id); $user_info = $this-db-get_row(); $this-id = $user_info['id']; $this-group_id = $user_info['group_id']; $this-login = $user_info['login']; $this-password = $user_info['password']; } } ... } I tried extending the user class from the project class, but that didn't work, because the $db var was empty. I tried changing it to static, but it didn't inherit the $db variable for some reason. So, how can I make this work, so I can write a bunch of classes that can blindly use $this-db or something similar without having to worry about setting it in the constructor? I thought about setting it as a global, but that didn't seem very... OOP. See here: http://www.php.net/manual/en/language.oop5.decon.php and note this: Note: Parent constructors are not called implicitly. In order to run a parent constructor, a call to parent::__construct() is required. ---John Holmes... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] PHP5 - OOP Question
Hello Group, I would like to know which one is the most appropriate way to implement the following scenario. For example, I want to display a products catalogue of 100 products. I do have a base class of product which contains all the basic property of the product (Product title, product description, product price etc)and constructor basically pulls the information about the product from the DB based on the product identifier (Primary key). Now i have two ways to display catalogue. 1. I can write only one query to pull all 100 products information and store product information to each product object (With out passing product id to the constructor) into the collection and later i iterate that collection to display product catalogue. (Advantage: less communication with database server and disadvantage: memory consumption is higher) 2. I can initiate an individual product object by passing product id into the constructor and constructor will pull an individual product information from the DB and at the same time i can display it (Disadvantage: Lots of communication with database server and Advantage: memory consumption is less) If you think about inheritance then eventually this approach will have lots of database calls. Please guide me as i am stuck up which way to go. Let me know if you need more information. Thanks, Hardik __ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 - OOP Question
On Mon, 2004-08-09 at 22:29, Hardik Doshi wrote: Hello Group, I would like to know which one is the most appropriate way to implement the following scenario. For example, I want to display a products catalogue of 100 products. I do have a base class of product which contains all the basic property of the product (Product title, product description, product price etc)and constructor basically pulls the information about the product from the DB based on the product identifier (Primary key). Now i have two ways to display catalogue. 1. I can write only one query to pull all 100 products information and store product information to each product object (With out passing product id to the constructor) into the collection and later i iterate that collection to display product catalogue. (Advantage: less communication with database server and disadvantage: memory consumption is higher) 2. I can initiate an individual product object by passing product id into the constructor and constructor will pull an individual product information from the DB and at the same time i can display it (Disadvantage: Lots of communication with database server and Advantage: memory consumption is less) If you think about inheritance then eventually this approach will have lots of database calls. Please guide me as i am stuck up which way to go. Let me know if you need more information. If you expect the products database to grow much, then solution 2 is your best bet to accommodate much larger numbers. If you expect that you will only ever have a couple of hundred then solution 1 will most likely work nicely. Either way, converting from one style to the other is merely a matter of iterating over retrieved database rows versus iterating over an array of pre-retrieved items. It should take you less time than it took you write your post :) Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 - OOP Question
On Mon, 2004-08-09 at 19:29, Hardik Doshi wrote: Hello Group, I would like to know which one is the most appropriate way to implement the following scenario. For example, I want to display a products catalogue of 100 products. I do have a base class of product which contains all the basic property of the product (Product title, product description, product price etc)and constructor basically pulls the information about the product from the DB based on the product identifier (Primary key). Now i have two ways to display catalogue. 1. I can write only one query to pull all 100 products information and store product information to each product object (With out passing product id to the constructor) into the collection and later i iterate that collection to display product catalogue. (Advantage: less communication with database server and disadvantage: memory consumption is higher) You can do both. You can create an object for products and have it designed to give you details for a specific product, and then you can have a function that will return products based on a filter... (sometimes your users want to search for products)..so the same query can be used but append a filter to it. 2. I can initiate an individual product object by passing product id into the constructor and constructor will pull an individual product information from the DB and at the same time i can display it (Disadvantage: Lots of communication with database server and Advantage: memory consumption is less) If you think about inheritance then eventually this approach will have lots of database calls. Please guide me as i am stuck up which way to go. Let me know if you need more information. Thanks, Hardik __ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail -- /*** * Robby Russell | Owner.Developer.Geek * PLANET ARGON | www.planetargon.com * Portland, OR | [EMAIL PROTECTED] * 503.351.4730 | blog.planetargon.com * PHP/PostgreSQL Hosting Development / -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] PHP5 - OOP Question
* Thus wrote Hardik Doshi: Hello Group, I would like to know which one is the most appropriate way to implement the following scenario. For example, I want to display a products catalogue of 100 products. I do have a base class of product which contains all the basic property of the product (Product title, product description, product price etc)and constructor basically pulls the information about the product from the DB based on the product identifier (Primary key). Now i have two ways to display catalogue. 1. I can write only one query to pull all 100 products information and store product information to each product object (With out passing product id to the constructor) into the collection and later i iterate that collection to display product catalogue. (Advantage: less communication with database server and disadvantage: memory consumption is higher) 2. I can initiate an individual product object by passing product id into the constructor and constructor will pull an individual product information from the DB and at the same time i can display it (Disadvantage: Lots of communication with database server and Advantage: memory consumption is less) If you think about inheritance then eventually this approach will have lots of database calls. Please guide me as i am stuck up which way to go. With these two options I can see why it is a tough choice. There is another option you can take. Store the result handle of the query from #1 into an object, and retrieve a row from the database on demand. abstract class DbIterator implements Iterator { /* for me only */ private $current = 0; private $data= false; private $handle = null; /* Force extending object to define this function */ abstract protected function getData($handle, $function); public function __construct($handle) { $this-handle = $handle; } /* Iterator Interface: */ public function rewind() { $this-current = 0; db_seek($this-result, $this-current); } public function current() { return $this-data; } public function key() { return $this-current; } public function next() { $this-data = $this-getData($handle, 'db_fetch_assoc'); if($this-data) { $this-current++; } return $this-data; } public function valid() { return (this-data !== false); } } class dbProductClass extends DbIterator { public $id; public $name; public function __construct($handle) { /* let the parent decide what to do with $handle */ parent::__construct($handle) } /* and define this required function */ protected function getData($handle, $func) { $row = $func($handle); if ($row == false ) { return $row; } $this-$id = $row['id'] if (empty($row['name']) { $this-name = 'Default Name'; } else { $this-name = $row['name']; } // do any special stuff here.. return $this; } public function tableName { return 'People'; } /* this is a no no */ public function __set($name, $value) { throw Execption(Attempt to write to readonly property); } } // then.. $result = db_query($sql); $product_rows = new dbProductClass($result); // then some more.. foreach($product_rows as $row ) { echo $row-field_name1; echo $row-field_name2; } This will keep communication down to a minimum and memory down to a minimum usage as well. I hope this wasn't to much, and it is completely untested. Curt -- First, let me assure you that this is not one of those shady pyramid schemes you've been hearing about. No, sir. Our model is the trapezoid! -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php