accessing vars from within classes
accessing vars from within classes
am 12.09.2007 19:03:27 von PaowZ
Hello there!
I'd like to make some declared vars available to classes, such as:
//main environment
$myVar = new MyClass(); //the var I want to be available to OtherClass
....
....
class OtherClass{
private $otherVar = $myVar; //seems to not work
...
}
?>
...and I wish to initialize $otherVar 'as is', I mean, without having
to pass arg through __construct(). The way I tried above doesnt seem
to work, unlike it would be in a function..
any idea ??
thanks a lot :)
Re: accessing vars from within classes
am 12.09.2007 20:47:38 von ragearc
Yep, I believe global would work.
PHP:
$myVar = new MyClass();
class OtherClass {
private $otherVar;
function myMethod() {
global $myVar;
$this->otherVar = $myVar;
}
}
Re: accessing vars from within classes
am 12.09.2007 20:53:55 von Shelly
I have a simple question, You are using classes because you want to be OO
rather than procedural. Why, then, would you expect what you did to work.
Instead, OtherClass should have accessor and mutator methods. It would bebe
executed as $otherClassInstance.setOtherVar($myVar) where
$otherClassInstance is and instance of OtherClass.
So, in summary, if you are procedual then stay procedural and if you are OO
then stay OO.
"PaowZ" wrote in message
news:1189616607.313148.113350@w3g2000hsg.googlegroups.com...
> Hello there!
>
> I'd like to make some declared vars available to classes, such as:
>
> //main environment
> $myVar = new MyClass(); //the var I want to be available to OtherClass
> ...
> ...
> class OtherClass{
> private $otherVar = $myVar; //seems to not work
> ..
> }
> ?>
>
> ..and I wish to initialize $otherVar 'as is', I mean, without having
> to pass arg through __construct(). The way I tried above doesnt seem
> to work, unlike it would be in a function..
>
> any idea ??
>
> thanks a lot :)
>
Re: accessing vars from within classes
am 13.09.2007 00:45:00 von nc
On Sep 12, 10:03 am, PaowZ wrote:
>
> $myVar = new MyClass(); //the var I want to be available to OtherClass
> ...
> ...
> class OtherClass{
> private $otherVar = $myVar; //seems to not work
> ..}
But of course. The scope of $myVar is lies outside OtherClass, so
$myVar is meaningless in the context of OtherClass.
> ..and I wish to initialize $otherVar 'as is', I mean,
> without having to pass arg through __construct().
And I wish to build a perpetual motion machine. Alas, the world does
not work that way...
> The way I tried above doesnt seem to work, unlike it would
> be in a function..
It wouldn't work in a function either, unless you declare $myVar as
global.
> any idea ??
Don't let your wishes control you; control your wishes instead.
Cheers,
NC
Re: accessing vars from within classes
am 13.09.2007 16:13:16 von PaowZ
Thanks for all replies..
> Don't let your wishes control you; control your wishes instead.
I'll try to think about it ^^ :)