Welcome to WebmasterWorld Guest from 54.196.232.162

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP Object-Oriented 'Best Practice' Question

instantiating objects

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

New User

5+ Year Member

joined:Sept 14, 2007
posts: 12
votes: 0


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.
7:15 am on Aug 31, 2010 (gmt 0)

Moderator from CA 

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

joined:Aug 29, 2003
posts:4059
votes: 0


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
10:04 pm on Sept 2, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Mar 19, 2009
posts:165
votes: 0


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. :)
2:47 pm on Sept 3, 2010 (gmt 0)

Moderator from CA 

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

joined:Aug 29, 2003
posts:4059
votes: 0


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
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members