-1

I'm totally new to php(migrating from java). There are two classes

First.php

class First {

    public function method(){
        #how to call second object like java
        #$obj=new Second();
    }
}

Second.php

class Second{
    public function method_second(){
        echo 'second method';
    }
}

Can't we create object of Second.php in First.php

Bruce
  • 8,609
  • 8
  • 54
  • 83

1 Answers1

3

You should include the Second.php file in the First.php to have access to the Second class:

<?php
include "Second.php";
class First {
    public function method(){
        #how to call second object like java
        $obj=new Second();
    }
}

Also you can use an autoloader ( not the best example :) ):

<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

class First {
    public function method(){
        #how to call second object like java
        $obj=new Second();
    }
}
?>

More info about autoloaders can be found on php.net: http://php.net/manual/en/language.oop5.autoload.php

Marin Bînzari
  • 5,208
  • 2
  • 26
  • 43
  • can we use without register autoload – Bruce May 12 '15 at 19:11
  • @Exbury, No, you are forced to choose between `include "Second.php";`, `require "Second.php";` or the `autoloader`. The PHP should know where the class is defined and these are methods you should use to tell where the class is located. – Marin Bînzari May 12 '15 at 19:12
  • Another question i have if add both classes with namespace Test\Src; Then how can we create object. if i used as this it throws exception Fatal error: Class 'Test\Src\Second' not found – Bruce May 12 '15 at 19:42
  • You can get more info in another question on SO http://stackoverflow.com/questions/1830917/how-do-i-use-php-namespaces-with-autoload – Marin Bînzari May 12 '15 at 19:48