1
<?php global $words; class A { function say() { global $words; $words = 'man'; A::hello(); A::bye(); echo $words; } function hello(){ global $words; $words .= 'hello'; } function bye(){ global $words; $words .= 'bye'; } } A::say(); ?> 

i think it is stupid, Can you pointed me a good way ?

9
  • 3
    you shouldn't be using a no longer supported version of php, its dangerous. from the manual "Support for PHP 4 has been discontinued since 2007-12-31. Please consider upgrading to PHP 5." Commented Jul 29, 2011 at 4:17
  • @Dagon: i know , but i have to care on php4 :D Commented Jul 29, 2011 at 4:22
  • 1
    what's the value of supporting php4? may as well support php3. Commented Jul 29, 2011 at 4:28
  • 1
    @Chameron , then change the boss. Commented Jul 29, 2011 at 6:38
  • 1
    @Chameron: teresko is (a kind of) right: If your boss doesn't know, what he is talking about, its also your job to tell him, that he is wrong (maybe in other words ;)). When something gets terrible wrong, because you use an outdated environment, its probably up to you to fix it (and with "terrible" I mean "terrible"). Commented Jul 29, 2011 at 8:43

2 Answers 2

2

Declare $words as a static variable within the class:

class A { static $words; static function say() { self::$words = 'man'; A::hello(); A::bye(); echo self::$words; } static function hello() { self::$words .= 'hello'; } static function bye() { self::$words .= 'bye'; } } A::say(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. Read more at: php.net/manual/en/language.oop5.static.php Note that PHP4 does not support access modifiers. Also, you might need to namespace references from $words to self::$words. Not sure if PHP makes you do that.
php4.4.6 : Parse error: parse error, unexpected T_STATIC, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}
1

PHP4 code (compatible with PHP5).

class A { var $words; function A($words) { $this->words = $words; } function say() { $this->words = 'man'; $this->hello(); $this->bye(); return $this->words; } function hello() { $this->words .= 'hello'; } function bye() { $this->words .= 'bye'; } } $a = new A($words); echo $a->say(); 

In general, you do not want to use the global keyword when doing OOP. Pass any dependencies through the ctor or via appropriate setters. Relying on globals will quickly introduce side effects into your application, breaks encapsulation and will make your API lie about it's dependencies. You should also avoid all static classes because they will tightly couple the calling class to the static class. This makes maintenance and testing more painful than it needs to be (same for globals).

Also see https://secure.wikimedia.org/wikipedia/en/wiki/Solid_(object-oriented_design)

1 Comment

Thanks, i have change the way i use class

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.