1

How can I create something like

MyObject->property->method()

in PHP?

I only know how to create a method for a class:

class MyObject
{
    public function MyMethod()
    {
       // do something
    }
}

In Javascript I can easily do something like

var MyObject = {
   property : {
     method : function ()
              {
                 // do something
              }
   }
}

How do I do that?

1
  • 1
    You can't call a method on a property. You access it with $this->property Commented Apr 3, 2015 at 7:42

3 Answers 3

2

In Javascript you can create objects and methods inline, in PHP you need to have a class and instantiate it:

class Foo {

    public function method() {}

}

class MyObject {

    public $property;

    public function __construct() {
        $this->property = new Foo;
    }

}

$o = new MyObject;
$o->property->method();
Sign up to request clarification or add additional context in comments.

1 Comment

So very neat that is :)
2

You can set an object as the value of a property. Something like this:

class Foo {
   public $Bar;

   public function __construct() {
       $this->Bar = new Bar(); 
   }
} 

class Bar {

   public function ShowBar() {
       echo 'Bar';
   }   

}

$Foo = new Foo();
$Foor->Bar->ShowBar();

Comments

0

As others have correctly answered, this works differently in PHP and Javascript. And these differences are also the reason why in PHP you need to define the class methods before you run them. It might become a bit more dynamic in the future but I'm sure not on the level of Javascript.

You can however fake this a bit in PHP because you can assign functions to properties dynamically:

$myObject = new PropCall;
$myObject->property->method = function() {
    echo "hello world\n";
};    

$myObject->property->method();

This example outputs:

hello world

This does work because some little magic has been added in the instantiated object:

class PropCall
{
    public function __call($name, $args) {
        if (!isset($this->$name)) {
            return null; // or error handle
        }
        return call_user_func_array($this->$name, $args);
    }

    public function __get($name) {
        $this->$name = new PropCall;
        return $this->$name;
    }
}

This class code checks if a dynamic property has been added with the name of the method called - and then just calls the property as a function.

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.