Calling a function within a function within a class
Having a little trouble with this one I think. I was able to succeed in the following manner but to to my satisfaction.
//============| CODE START |==============//
class myclass{
//first function example
function first_fn(){
instuctions
}
//second function example calling first function within the same class
function second_fn(){
instuctions of second function
$use_fn= new myclass();
$use_fn->first_fn();
}
}
//============| CODE END |==============//
This worked for me but its it the correct way of calling that first function? I don't think it is because the result is showing in the location of which the second function result has been placed which isn't what I want.
I want to call the second function and have the result display in the place of the second function.
class myClass {
function first_fn() {
//instructions
}
function second_fn(){
//instuctions of second function
$this->first_fn();
}
}
$myObj = new myClass;
$myObj->second_fn(); //according to your code this will call second_fn which will call first_fn();
You need to use the this keyword which makes an object refer to itself.
Your code would not have done that, because an object created from an instantiation of myclass would have instantiated a second instance when second_fn() was called.
I'm far from an expert (or even a novice) at OOP, but from your code I'd suggest googling around for a tutorial or two, or perhaps pick up a book, on OOP with PHP.
Last edited by aj_nsc; 08-13-2010 at 11:48 AM.
I've switched careers...
I'm NO LONGER a scientist,
but now a web developer...
awesome.
Using $this->method_name() would be correct in the vast majority of cases, rather than creating another instance of the class. Occasionally you might instead use self::method_name() in a situation where the first method is defined as static, but that would not be the case here.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks