Re: Globalizing vars in class methods doesnt seem to work, var disappears after global, var is inaccessible in other methods/funcs [message #178794 is a reply to message #178793] |
Sat, 04 August 2012 18:45 |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 8/4/2012 2:24 PM, Jerry Stuckle wrote:
> On 8/3/2012 1:45 PM, J. Frank Parnell wrote:
>> <?php
>> class test{
>> function __construct(){
>> $this->makevar();
>> global $var;
>> echo '<hr>__const(): '.$var;
>> }
>> function makevar(){
>> $var = 'something';
>> echo '<hr>just declared in makevar(): '.$var;
>> global $var;
>> echo '<hr>after global in makevar(): '.$var;
>> }
>> }//class
>>
>> $t = new test;
>> echo '<hr>outside class: '.$var;
>> global $var;
>> echo '<hr>outside class after global: '.$var;
>>
>> ?>
>> this outputs:
>> just declared in makevar(): something
>> after global in makevar(): [nothing]
>> __const():[nothing]
>> outside class: [nothing]
>> outside class after global: [nothing]
>>
>>
>> So, 1, why does global $var in the makevar() make it null?
>> and B, why dont I have any access to $var in the __constructor or
>> outside the class?
>>
>> In the real script, $var will be an instance of a different class that
>> I want to use all over the place.
>>
>> thanks, J
>>
>
> And what if you have:
>
> $t1 = new test;
> $t2 = new test;
>
> Which variable are you supposed to be referencing (they are two
> different variables)?
>
> But what you're doing violates several concepts in OO programming,
> including encapsulation and message passing. The correct way to do it
> is to pass an object of the class as a parameter (i.e. to the
> constructor) then use getters and setters to reference the variable.
> Proper coding makes your code more reliable, maintainable, reusable and
> easier to understand.
>
An addition option I forgot to mention - you could also use the
singleton pattern as M. Strobel referenced. However, if you do, you
should always have a default parameter in the call so you can use
something other than the singleton when you need to.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
|
|
|