3

In JS you can access methods in this fashion: ParentObject.ChildObject.ChildObjMethod() -- can same be done in PHP?

mvbl fst
  • 5,213
  • 8
  • 42
  • 59
  • What is `ParentObject`, and what is `ParentObject::ChildObject`? Are either of them classes, or is one or both an instance in its own right? – Matchu Dec 26 '10 at 19:44
  • well ok, I am wondering if a static class (object) can have a nested static class with certain methods. Typically you can use them like Class::method() but can Class have a nested SubClass that I can access as I described above -- Class::SubClass::SomeMethod() or not? – mvbl fst Dec 26 '10 at 19:53
  • No, you can't store a reference to a class in a variable in PHP, or return a class from a method call. Classes aren't "first class objects" in this sense in PHP. – Alana Storm Dec 26 '10 at 21:05

2 Answers2

2

Not exactly. The :: operator is for invoking static methods on a class. So, you could store a reference to an object statically, but then you'd need to invoke the method with a -> operator.

<?php
    class Foo
    {
        static public $bar;

        static public function initStaticMembers()
        {
            self::$bar = new Bar();     
        }
    }

    class Bar
    {
        public function method()
        {
            echo "Hello World\n";
        }

    }

    Foo::initStaticMembers();
    Foo::$bar->method();

There's no way to do

    Object::ChildObject::method();

Method chaining is essentially a shortcut for something like

    $o = Object::ChildObject;
    $o::method();

The first call is made, and returns or assigns something. The next method is then called on the thing that's returned. You can't store a class in a variable with PHP, or return a class from a function. Therefore, the exact syntax for what you're asking to do is impossible.

That said, method chaining is becoming more popular in PHP. Syntax like the following

    $o = new Baz();
    $o->method()->anotherMethod()->yetAnotherMethod();
    $o->someObjectReference->methodCall()->etc();

is becoming common place. This works because each call or variable reference

    $o->method();
    $o->someObjectReference;

returns another Object instance, which can then have a method called on it.

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
1

The :: can be used for accessing static class members. But you can also access instantiated childobjects in PHP, using the normal -> arrow thingy:

$parent->child->child_method();

See also Reference - What does this symbol mean in PHP?

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291