Jump to content

Class call in a function


yanviau

Recommended Posts

Hola to all php coder,

 

Probably an easy one for you.

 

Page.php

 

include ('class/general.php');

$instance = new General();

 

function something()

{

$instance->check()

}

 

 

general.php

<?php

 

class General

{

function check()

{

echo "world";

}

}

 

Why the call of my class function doesnt work ?

when my class declaration is outside the function = BOUM error

When my class declaration is inside my function = working

 

So i understand the fact than i need a global variable or something like that but i try to

include ('class/general.php');

global $instance;

$instance = new General();

 

And it's not the solution.

 

Someone have any tips ?

 

Sorry for my english.

 

Link to comment
https://forums.phpfreaks.com/topic/207721-class-call-in-a-function/
Share on other sites

You need to familiarize yourself with the concept of variable scope

http://php.net/manual/en/language.variables.scope.php

 

In your example

 

include ('class/general.php');
$instance = new General();

function something($object)
{
$object->check()
}

something($instance);

i would like prefer to have a variable that i don't need to pass in the function if it's possible.

Why? That's how functions are supposed to be written. You can use a global statement, but then you are limiting the usefulness of the function.

 

Ken

Sorry maybe some feedback from other language, im new with php  :confused:

 

in my mind the easiest and normal thing is something like this but i know it's doesn't work.

 

include ('class/general.php');

global $instance = new General();

 

function something()

{

$instance->check()

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.