2

I need to know something about OOP in PHP.
Can I put functions in class methods or no ? Like this:

<?php
class test {
   function test1() {

      // do something

      function test1_1() {
         // something else
      }

   }
}
?>

And use it in this way: $test->test1->test1_1();

0

4 Answers 4

3

No you cannot. That would just create a new function in the global namespace and will give you errors of trying to redeclare the function when called multiple times.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually, it doesn't get created in the global namespace. It gets created in the method scope only. The function won't exist outside of that method call. But the message about errors is true.
No when I say global namespace I mean global namespace :)
Right, only after calling the method once. Okay, I suppose that's fair.
So...don't blame you for PHP?
2

You can put functions inside of methods (look up closures). However, you cannot call them this way.

An example of a closure would be

class MyClass {
    public function myFunction() {
        $closure = function($name) {
            print "Hello, " . $name . "!";
        };

        $closure("World");
    }
}

Comments

1

You can use closures (>=PHP5.3) to store functions in variables.

For example:

class Test {

    public $test1_1;

    public function test1() {
        $this->test1_1 = function() {
            echo 'Hello World';
        };
    }

    public function __call($method, $args) {
        $closure = $this->$method;
        call_user_func_array($closure, $args);
    }
}

$test = new test();
$test->test1();
$test->test1_1();

Or you could create another object with the function you want and store that in Test.

class Test {
    public $test1;
    public function __construct(Test1 $test1) {
        $this->test1 = $test1;
    }
}

class Test1 {
    public function test1_1 {
        echo 'Hello World';
    }
}

$test1 = new Test1();
$test = new Test($test1);
$test->test1->test1_1();

I don't see what you would accomplish by writing a function within another function. You might as well write two functions.

Comments

0

No you can't call test1_1 like that. When you define any variable or function in a function, that goes being local for only place that defined in.

Therefore, only this will work;

class test {
   function test1($x) {
      $test1_1 = function ($x) {
        return $x*2;
      };
      echo $test1_1($x) ."\n";
   }
}

// this will give 4
$test->test1(2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.