Results 1 to 3 of 3

Thread: Calling a function within a function within a class

  1. #1
    Join Date
    Jun 2006

    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(){

    //second function example calling first function within the same class
    function second_fn(){
    instuctions of second function
    $use_fn= new myclass();


    //============| 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.


  2. #2
    Join Date
    Dec 2005
    class myClass {
    function first_fn() {
    function second_fn(){
    //instuctions of second function
    $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 12:48 PM.
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...

  3. #3
    Join Date
    Aug 2004
    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.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

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