www.webdeveloper.com
Results 1 to 3 of 3

Thread: Calling a function within a function within a class

  1. #1
    Join Date
    Jun 2006
    Posts
    46

    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.

    If anyone can help, I'd greatly appreciate it.

    sonicpaint

  2. #2
    Join Date
    Dec 2005
    Posts
    2,984
    Code:
    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.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    18,924
    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

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles