/    Sign up×
Community /Pin to ProfileBookmark

question about php classes.

When including one class in another, what’s the difference between these two codings(the first line in func1())?

[code=php]class One {
public $var1;
function func1() {
global $sample;
//do something with class Two;
}
}
class Two {
public $var2;
}
$sample = new Two;

————————————————————————
class One {
public $var1;
function func1() {
$sample = new Two;
//do something with class Two;
}
}
class Two {
public $var2;
}[/code]

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@TheRaveDec 04.2007 — When including one class in another, what's the difference between these two codings(the first line in func1())?
[/QUOTE]


In the first example $sample is initialised outside of class One.

In the second example $sample is initialised within class One.

It depends what you want the scope of $sample to be. In the second example $sample will only be accessible within that function. In the first example it can be acessible globally.

If you don't need it globally then use the second example.
Copy linkTweet thisAlerts:
@ss1289authorDec 04.2007 — In the first example $sample is initialised outside of class One.

In the second example $sample is initialised within class One.

It depends what you want the scope of $sample to be. In the second example $sample will only be accessible within that function. In the first example it can be acessible globally.

If you don't need it globally then use the second example.[/QUOTE]

So basically, in the second example, if I wanted to use $sample in another function then I'd have to pass it to that function as an argument? Where as in the first example I just have to enter "$gobal $sample" in every function I use it in?
×

Success!

Help @ss1289 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...