How can I use variable from the outside of the class? For example:

<?php
   $outside = 'Hello';

   class A {
       function printme() {
           print $outside;
       }
    }

   $cls = new A();
   $cls->printme();
?>

How can I do it? please :D

Hi. You can use :

function printme() {

           global $outside;
           print $outside;    }

- Mitko Kostov

Oh thanks you :)

Yes.. because within a function, it has it's own scope issues, if you use the global keyword, you can access vairables/stuff outside the scope of this function.

Thus, doing a global of your $outside vairable, makes it local within your function.
However, if you change the value of $outside, it will be changed globally, not locally in the function...

Another method would be passing the $outside variable as a paramtere to the function like so..

$variable = "hello";
 
function printme($variable) {
 
    print $variable;
}

Any questions. just ask.
Cheers.

Another question:

class A{
		public $msg = '';

		public function set_msg($new_msg) {
			global $msg;
			$msg = $new_msg;
		}
	}

	$message = new A();
	$message->set_msg('Hello World');
	print $message->msg;

Why this code doesn't work as what I expect

What happens when you print it ?

Probally, nothing is printed. EMPTY :D

You should use

$this->msg = $new_msg;

instead of

$msg = $new_msg;

- Mitko Kostov

commented: Very helpful person +3

Worked!!! Thanks you... sorry to ask many question... :D
But I am really new at that CLASS system in PHP :D thanks
ago.

Yes, that's correct.

You've declared $msg as an instance variable of the class, so to refer to it you would do $this->variable.
Same if u have another function in the same class, you could call it by doing $this->function();

Not a problem dude, i have nothing else to do :)
Ask away.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.