Jump to content

understanding functions and classes


CyberShot

Recommended Posts


class person {
var $name = "Jimmy Goe";

function get_name(){

	echo $this->name;
}
}

 

  I am playing with this very small script that I made using a tutorial. I can get the script to echo out the name using the code above. What I don't get is why I can't do this

 

class person {
var $name;

function get_name(){
	$name = "Jimmy Goe"
	echo $this->name;
}
}

 

then of course in my index page, I am calling it like this

$joe = new person();

$joe->get_name();

 

If you decide to answer this question, please be as detailed as possible, I am a newb as you can see and the more information you give or the simpler the explanation, the better.

 

Thanks for helping

Link to comment
https://forums.phpfreaks.com/topic/179153-understanding-functions-and-classes/
Share on other sites

i think its because of the scope of a function.

i.e.

function get_name(){
      $name = "Jimmy Goe"
      echo $this->name;
   }

 

$name within the function and $name in the class are two separate variables, because the scope of a variable within a function is local..

 

 

try

 

function get_name(){
      $this->name = "Jimmy Goe"
      echo $this->name;
   }

yes, that works. but it defeats the purpose of the variable in the class. What I am trying to learn here is why the variables are assigned in the class. I thought it was because they were to be properties for the methods. $this only gives access to the method and not the class right?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.