Search code examples
phpsyntaxscoperesolutionoperator-keyword

PHP - Achieve certain syntax with multiple classes


(PHP7) I have two classes but would like to access one class inside of another for example:

Syntax: Property::House()->getAddress();

class Property
{
  protected $House;
  function Property()
  {
    self::$House = new House();
  }

  public function House()
  {
     return self::$House;
  }
}
class House
{
  public function getAddress()
  {
     // code
  }
}

does anyone know to accomplish this?, the syntax needs to be the same but the classes can change if needed


Solution

  • Firstly, your class setup is going to give you deprecation errors in PHP7. You'd be better off using the __construct() method in place of Property() if you're wanting to use non-static calls.

    Secondly. Are you sure you don't want House to extend the Property class instead of being a property of the Property class?

    Thirdly, assuming you're sure of what you're trying to achieve this should work...

    <?php
        class Property
        { 
    
            static function House()
            {
                return new House();
            }
        }
    
        class House
        {
            public function getAddress()
            {
                echo 'YAY!';
            }
        }
    
        Property::House()->getAddress();