如何使用PHP在另一个类中调用方法


How to call method within another class using PHP

我分别创建了两个php类。它们是Student.php和Main.php这是我的代码。

这是我的Student.php

<?php
class Student {
private $name;
private $age;
function __construct( $name, $age) {
    $this->name = $name;
    $this->age = $age;
}
function setName($name){
    $this->name = $name;
}
function setAge($age){
    $this->age = $age;
}
function getName() {
    return $this->name;
}
function getAge() {
    $this->age;
}
function display1() {
    return "My name is ".$this->name." and age is ".$this->age;
}
}
?>

这是我的Main.php

<?php
class Main{
function show() {
    $obj =new Student("mssb", "24");
    echo "Print :".$obj->display1();
}
}
$ob = new Main();
$ob->show();
?>

所以我的问题是,当我调用taht show方法时,它会出现致命错误:找不到类"Student"这里有什么问题。有必要进口什么的吗?请帮帮我。

添加

require_once('Student.php') 

在Main.php-file中(顶部)或在包含任何其他文件之前。。。

PHPUnit文档说,过去常说包含/需要PHPUnit/Framework.php,如下所示:

require_once ('Student.php');

从PHPUnit 3.5开始,有一个内置的自动加载器类可以为您处理这个问题:

require_once 'PHPUnit/Autoload.php'

您可以使用require_one('Student.php'),也可以使用PHP5的新功能命名空间。例如,假设您的Student.php位于一个名为Student的目录中。然后,作为Student.php的第一行,您可以放置

<?php    
namespace student;
class Student {
}

然后在您的Main.php 中

<?php    
use student'Student;
class Main {
}

值得一看PSR。特别是PSR-1

其中一个建议是

文件应该声明符号(类、函数、常量、,等等)或引起副作用(例如生成输出、change.ini设置等),但不应同时进行

遵循这一指导原则有望减少你遇到的问题。

例如,通常只有一个文件负责加载所有必要的类文件(最常见的是通过自动加载)。

当脚本初始化时,它应该做的第一件事就是包含负责加载所有必要类的文件。