mssb
mssb

Reputation: 878

How to call method within another class using PHP

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.

Upvotes: 1

Views: 4948

Answers (4)

Gihan De Silva
Gihan De Silva

Reputation: 467

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 {
}

Upvotes: 2

Shad
Shad

Reputation: 15471

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.

Upvotes: 0

TheHe
TheHe

Reputation: 2972

add

require_once('Student.php') 

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

Upvotes: 2

vikiiii
vikiiii

Reputation: 9476

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'

Upvotes: 2

Related Questions