在PHP中使用OOP时在方法中使用函数

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

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.

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");
    }
}

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) ."
";
   }
}

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

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.