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
Share on other sites

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

Link to comment
Share on other sites

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()

}

Link to comment
Share on other sites

Yeah, different languages have different approach towards variable scope. In PHP scopes are isolated. Variables from outside are not visible inside a function. In JavaScript they are, but can be overriden by local variables.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.