sorenchr Posted June 13, 2009 Share Posted June 13, 2009 Hey there. I'm having a hard time figuring this one out. Say I want to output "2 Hammers in toolshed", when I call the $toolshed->inventory() function, how should the code then look? class toolshed { function inventory() { echo $amount->hammers()." ".$toolname->hammer()." in toolshed"; } } class amount { function hammers() { return "2"; } } class toolname { function hammer() { return "Hammers"; } } $toolshed = new toolshed(); $amount = new amount(); $toolname = new toolname(); echo $toolshed->inventory(); This currently outputs: Fatal error: Call to a member function hammers() on a non-object in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\test.php on line 6 I know the functions seem retarded, but I'm trying to illustrate a much more complex problem I'm currently experiencing with my code. Thanks for your time Quote Link to comment https://forums.phpfreaks.com/topic/162028-php-oop-difficulties/ Share on other sites More sharing options...
youngmonkey Posted June 13, 2009 Share Posted June 13, 2009 The class toolshed has no idea what $amount or $toolshed is. You need to instantiate the classes amount and toolname INSIDE the class toolshed. The corrected code (Tested to work): <?php class toolshed { function inventory() { $amount = new amount(); $toolname = new toolname(); echo $amount->hammers()." ".$toolname->hammer()." in toolshed"; } } class amount { function hammers() { return "2"; } } class toolname { function hammer() { return "Hammers"; } } $toolshed = new toolshed(); echo $toolshed->inventory(); ?> HTH, M. Quote Link to comment https://forums.phpfreaks.com/topic/162028-php-oop-difficulties/#findComment-854977 Share on other sites More sharing options...
.josh Posted June 13, 2009 Share Posted June 13, 2009 Your most immediate problem is scope. You have a method in a class trying to call a method from an object. Well objects work just like regular variables as far as scope (mostly...). You have to pass the object to the function (or instantiate it inside the class, as ^^ mentioned) Your less immediate problem is...well I mean, I know you said this is just an illustration, but if your real code is anything like this illustration, I have to wonder about how you have the real thing setup in the first place... Quote Link to comment https://forums.phpfreaks.com/topic/162028-php-oop-difficulties/#findComment-854978 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.