papaface Posted April 19, 2009 Share Posted April 19, 2009 Hello, I have a situation where I am wanting to access a class which is declared in my code from within another class. e.g class someRandomclass { function myName() { return "Andrew"; } } $example = new someRandomclass(); class anotherRandomclass { function bothNames() { echo $example->myName() . " randomer"; } } $example2 = new anotherRandomclass(); echo $example2->bothNames(); Obviously this is a ridiculous example, but it demonstrates what I am trying to achieve, however it wont work. Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/154791-solved-access-a-class-from-inside-another-class/ Share on other sites More sharing options...
Maq Posted April 19, 2009 Share Posted April 19, 2009 You need to use "extends" and call the desired function from the extended class with parent: class someRandomclass { function myName() { return "Andrew"; } } class anotherRandomclass extends someRandomclass { function bothNames() { echo parent::myName() . " randomer"; } } $example2 = new anotherRandomclass(); echo $example2->bothNames(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/154791-solved-access-a-class-from-inside-another-class/#findComment-813994 Share on other sites More sharing options...
papaface Posted April 19, 2009 Author Share Posted April 19, 2009 Thanks for that. Does the class you're wanting to extend need to be in the same file? Currently I have two includes. The first include contains the class I am wanting to extend upon. I am getting a Class not found error. Quote Link to comment https://forums.phpfreaks.com/topic/154791-solved-access-a-class-from-inside-another-class/#findComment-814001 Share on other sites More sharing options...
papaface Posted April 19, 2009 Author Share Posted April 19, 2009 Ah correction. I was including them in my main file in the wrong order LOL That works. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/154791-solved-access-a-class-from-inside-another-class/#findComment-814002 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.