使用类中的方法创建类?

I would like to create a property which is a class in and of itself and add other methods to it within the "parent" class MyName, so that I would be able to do something like

$myname = new MyName();
$myname->event->post($params);

I've tried the following, but it doesn't work:

class MyName {
    public function __construct() {
        $this->event = new stdClass();
        $this->event->post = function($params) {
            print_r($params);
        };
    }
}

$x = new MyName();
$x->event->post(array(1, 2, 3));

Which simply ends up flagging the following fatal error:

Fatal error: Call to undefined method stdClass::post() in C:\xampp\htdocs\Arkwayecreation\primepromotions\api\classes\FacebookWrapper.php on line 25

You could use __call to access an internal array of closures, perhaps something like this:

class MyName {
  public function __construct() {
     $this->event = new EventObj();
     $this->event->post = function($params) {
          print_r($params);
      };
  }
}

class EventObj {

  private $events = array();

  public function __set($key, $val) {
    $this->events[$key] = $val;
  }

  public function __call($func, $params) {
     if (isset($this->events[$func])) {
       call_user_func_array($this->events[$func], $params);
     }
  }
}


$x = new MyName();
$x->event->post(array(1, 2, 3));

Output:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
)

You can't do that in PHP.

You can either create another class and then initialize it in the main class and access it through a variable or you can simulate method chaining if you want to keep the code all inside one object. This article http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html shows one way of method chaining in PHP.

You can do this way:

class MyName extends stdClass{

or

class MyName {
    public function getStdClass(){
        return new StdClass();
    }

And you can call:

$test = new MyName();
$test->someStdClassMethod();

or

$test = new MyName();
$test2 = $test->getStdClass();
$test2->someStdClassMethod();

Respective.