PHP: Calling another class' method

后端 未结 4 1982
别跟我提以往
别跟我提以往 2020-12-23 09:50

I\'m still learning OOP so this might not even be possible (although I would be surprised if so), I need some help calling another classes method.

For example in

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 10:38

    You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA

    class ClassA {
        public function getName() {
          echo $this->name;
        }
    }
    
    class ClassB extends ClassA {
        public function getName() {
          parent::getName();
        }
    }
    

    Without inheritance or an instance method, you'd need ClassA to have a static method

    class ClassA {
      public static function getName() {
        echo "Rawkode";
      }
    }
    

    --- other file ---

    echo ClassA::getName();

    If you're just looking to call the method from an instance of the class:

    class ClassA {
      public function getName() {
        echo "Rawkode";
      }
    }
    

    --- other file ---

    $a = new ClassA();
    echo $a->getName();
    

    Regardless of the solution you choose, require 'ClassA.php is needed.

提交回复
热议问题