Welcome to WebmasterWorld Guest from 54.167.85.221

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP Object-Oriented 'Best Practice' Question

instantiating objects

     

adephue

7:34 pm on Aug 26, 2010 (gmt 0)

5+ Year Member



I have a question about how PHP classes relate to each other. Specifically, I am hoping to discern if a certain practice is unfavorable. In my example I have two classes, 'foo' and 'bar'.

class bar {
function talk () {$this->talk = 'Hello!';}
}

class foo {
function foo () {
bar::talk();
self::talk();
}
function talk () {echo $this->talk;}
}

$foo = new foo(); // This will echo 'Hello!' to the screen
echo '<p><pre>';
var_dump($foo);


If you run the posted code, the property 'talk' is assigned to object 'foo' even though the code is in object 'bar'. Or stating it another way, by calling bar::talk(); from within the context of object 'foo', I am able to utilize the functionality of object 'bar' within the context of object 'foo'. I never instantiate 'bar' with the new keyword.

So my question is whether or not this is a bad or non-standard OOP practice. I am doing some development this way but before I go much further I want to know if there is some big no-no or caveat that I am missing.

httpwebwitch

7:15 am on Aug 31, 2010 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member



nothing wrong with what you're doing. but you might want to EXTEND the class instead of calling functions from it.

if foo is intended to inherit the properties and methods of bar, then foo should extend bar.

the classic example: the dog that is an animal

class DOG extends ANIMAL {
var $age;

function talk() {
echo "bark! bark!";
}
}

calling bar::talk() from within foo is fine, but if your class structures get more complex than this then it could get confusing

CyBerAliEn

10:04 pm on Sep 2, 2010 (gmt 0)

5+ Year Member



class DOG extends ANIMAL {
var $age;

function talk() {
echo "bark! bark!";
}
}


This is my favorite example of coding, ever! I got a good laugh from reading this. :)

httpwebwitch

2:47 pm on Sep 3, 2010 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Most thorough books on PHP5 will have a chapter on OOP. It's worthwhile to become familiar with inheritance even if you don't delve deeply into advanced OOP. Every time I learn a new OOP technique (and I am still learning), it makes everything simpler, and I wish I'd studied OOP more thoroughly, earlier!

One guide I turn to often is the Visual QuickPro Guide to PHP 5 by Larry Ullman, Peachpit Press 2007
 

Featured Threads

Hot Threads This Week

Hot Threads This Month