1

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\Arkway\recreation\primepromotions\api\classes\FacebookWrapper.php on line 25
PeeHaa
  • 66,697
  • 53
  • 182
  • 254
Kemebear
  • 239
  • 1
  • 4
  • 11

3 Answers3

1

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
)
Martin
  • 6,362
  • 4
  • 21
  • 28
  • Fixed - why do you care so much about my answer? – Martin Feb 01 '13 at 19:39
  • 1
    Sorry my bad. +1, trick with `__set` is even bether technique. It will be good if you can mention [how to use anonymous functions](http://pastebin.com/G4vmyDRw) without `call_user_func_array` – Peter Feb 01 '13 at 19:45
0

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.

John McKnight
  • 624
  • 3
  • 8
-1

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.

Guerra
  • 2,777
  • 1
  • 19
  • 32