Class not in scope in another file

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Idiot88
New php-forum User
New php-forum User
Posts: 19
Joined: Thu Jan 25, 2018 2:56 pm

Tue Feb 06, 2018 6:14 pm

Hi

I create a class in file1 using:

global $p;
$p = new myclass();

The class is defined in a file2. In file3 I do:

global $p;
$p->my_member_function();

But it gives an error: call to a member function on null.
Does that mean $p is not in scope? How do I fix it?

Thanks.

chorn
php-forum Fan User
php-forum Fan User
Posts: 559
Joined: Fri Apr 01, 2016 2:18 am

Tue Feb 06, 2018 10:26 pm

your example is incomplete. this works:

scratch_8.php

Code: Select all

<?php

class myclass {
    function my_member_function(){
        echo 'works';
    }
}

global $p;
$p = new myclass();
scratch_9.php

Code: Select all

<?php

require 'scratch_8.php';

function something(){
    global $p;
    $p->my_member_function();
}

something();
you should consider using Dependency Injection for a more comprehensible code.

Post Reply