views:

894

answers:

4

I have been trying to figure out how to go about doing this but I am not quite sure how.

Here is an example of what I am trying to do:

class test {
     public newTest(){
          function bigTest(){
               //Big Test Here
          }
          function smallTest(){
               //Small Test Here
          }
     }
     public scoreTest(){
          //Scoring code here;
     }
}

Here is the part I am having problems with, how do I call bigTest()?

+3  A: 

You need to call newTest to make the functions declared inside that method “visible” (see Functions within functions). But that are then just normal functions and no methods.

Gumbo
+7  A: 

Try this one:

class test {
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }

     private function bigTest(){
          //Big Test Here
     }

     private function smallTest(){
          //Small Test Here
     }

     public function scoreTest(){
          //Scoring code here;
     }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();
Sergey Kuznetsov
+1 for being much cleaner than the whole function in a function way, imo.
GSto
A: 

In order to have a "function within a function", if I understand what you're asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

So you could have:

public function newTest() {
   $bigTest = function() {
        //Big Test Here
   }
}
blockhead
A: 

The sample you provided is not valid PHP and has a few issues:

public scoreTest() {
    ...
}

is not a proper function declaration -- you need to declare functions with the 'function' keyword.

The syntax should rather be:

public function scoreTest() {
    ...
}

Second, wrapping the bigTest() and smallTest() functions in public function() {} does not make them private — you should use the private keyword on both of these individually:

class test () {
    public function newTest(){
        $this->bigTest();
        $this->smallTest();
    }

    private function bigTest(){
        //Big Test Here
    }

    private function smallTest(){
           //Small Test Here
    }

    public function scoreTest(){
      //Scoring code here;
    }
}

Also, it is convention to capitalize class names in class declarations ('Test').

Hope that helps.

pjbeardsley