【问题标题】:How to call method within another class using PHP如何使用 PHP 在另一个类中调用方法
【发布时间】:2012-08-21 02:30:49
【问题描述】:

我分别创建了两个 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 方法时,它会给出 致命错误:未找到“学生”类这里出了什么问题。有必要进口吗?请帮帮我。

【问题讨论】:

    标签: php


    【解决方案1】:

    添加

    require_once('Student.php') 
    

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

    【讨论】:

      【解决方案2】:

      PHPUnit documentation说以前说的是include/require PHPUnit/Framework.php,如下:

      require_once ('Student.php');
      

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

      require_once 'PHPUnit/Autoload.php'
      

      【讨论】:

        【解决方案3】:

        你可以使用 require_once('Student.php') 或者你可以使用 PHP5 的新特性 namespaces。例如,假设您的 Student.php 在名为 student 的目录中。然后作为 Student.php 的第一行你可以放

        <?php    
        namespace student;
        
        class Student {
        }
        

        然后在你的 Main.php 中

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

        【讨论】:

          【解决方案4】:

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

          其中一个建议是

          文件应该声明符号(类、函数、常量、 等)或引起副作用(例如生成输出、更改 .ini 设置等),但不应该两者都做

          遵循本指南有望使您遇到的问题变得不那么常见。

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-06-27
            • 1970-01-01
            • 2013-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-14
            相关资源
            最近更新 更多