PHP:调用另一个类的方法 [英] PHP: Calling another class' method

查看:59
本文介绍了PHP:调用另一个类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习OOP,因此甚至不可能实现(尽管如果这样我会感到惊讶),但我需要一些帮助来调用另一个类方法.

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.

例如在ClassA I中具有此方法:

function getName()
{
    return $this->name;
}

现在从ClassB(不同的文件,但是在同一目录中),我想调用ClassAgetName(),我该怎么做?我试图做一个include(),但是那没用.

now from ClassB (different file, but in the same directory), I want to call ClassA's getName(), how do I do that? I tried to just do an include() but that does not work.

谢谢!

推荐答案

//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>

这篇关于PHP:调用另一个类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆