1

I created two php classes separately. those are Student.php and Main.php this is my code.

this is my 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;
}

}

?>

this is my Main.php

<?php

class Main{

function show() {
    $obj =new Student("mssb", "24");
    echo "Print :".$obj->display1();
}

}

$ob = new Main();
$ob->show();

?>

so my problem is when I call taht show method it gives Fatal error: Class 'Student' not found what is the wrong in here. is it necessary to import or something? please help me.

4 Answers 4

2

add

require_once('Student.php') 

in your Main.php-file (on top) or before the inclusion of any other file...

Sign up to request clarification or add additional context in comments.

Comments

2

The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:

require_once ('Student.php');

As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:

require_once 'PHPUnit/Autoload.php'

Comments

2

You can use require_once('Student.php') or you can use PHP5 new feature namespaces for that. For a example assume your Student.php is in a dir called student. Then as the first line of Student.php you can put

<?php    
namespace student;

class Student {
}

Then in your Main.php

<?php    
use student\Student;

class Main {
}

Comments

0

It's worth taking a look at the PSRs. Particularly PSR-1

One of the recommendations is that

Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both

Following this guideline will hopefully make issues like the one you're having less common.

For example, it's common to have one file that is just in charge of loading all necessary class files (most commonly through autoloading).

When a script initializes, one of the first things it should do is to include the file in charge of loading all necessary classes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.