Jump to content

New to PHP - bit confused with variables logic


wilsonf1

Recommended Posts

Hi - im converting some code from ASP to PHP which im enjoying learning - however im struggling with a bit of logic for calling some variables from different functions.I have a class - and a function called WebsiteDetails which retrieves site info from the database and sets some variables - i want to use these variables in other functions like editing pages, uploading pages - but how do I call on those variables - they don't seem to be able to see each other?

<?phpclass CMS {		public $db;	function WebsiteDetails($qsWebsite) {				$this->db->connect();		$sql = "SELECT * FROM cms_websites WHERE folder = '$qsWebsite' ";		$rs = $this->db->query($sql);		$exists = false;				while ($row = $this->db->row_read($rs)) {			$WebsiteId = $row['id'];			$WebsiteName = $row['website_name'];			$FullDomain = $row['full_domain'];			$Folder = $row['folder'];			$FtpHost = $row['ftp_host'];			$FtpUsername = $row['ftp_username'];			$FtpPassword = $row['ftp_password'];			$FtpRoot = $row['ftp_root'];		}					}		function DoSomething() {				echo "hello".$WebsiteName;			}		}?>

My index.php page:

// Set website variables$CMS->WebsiteDetails($qsWebsite);$CMS->DoSomething();

Notice: Undefined variable: WebsiteName in C:\wamp\www\CMS\objects\cms.php on line 28hello

Link to comment
Share on other sites

You want to set them as properties (a.k.a. fields, attributes, member variables, etc.) of the class. E.g.

private $websiteName;

$this->websiteName = $row['website_name'];

echo "hello".$this->websiteName;

Note that only classes (and constants) are supposed to start with uppercase letters - members should use lowerCamelCase or under_scores.

Link to comment
Share on other sites

You want to set them as properties (a.k.a. fields, attributes, member variables, etc.) of the class. E.g.
private $websiteName;

$this->websiteName = $row['website_name'];

echo "hello".$this->websiteName;

Note that only classes (and constants) are supposed to start with uppercase letters - members should use lowerCamelCase or under_scores.

worked a ruddy treat - thanks!!!however.......once i've set $websiteName; - is there anyway for another class to call on that property?tried: setting public $websiteName and then trying $CMS->websiteName from a new class after it was set but get undefined variablethanks!
Link to comment
Share on other sites

$CMS would not (automatically) exist inside the other class's scope, so the best way would be to pass the instance to it:

class OtherClass {	function getWebsiteNameOfCmsInstance($cms) {		return $cms->websiteName;	}}

$otherClass = new OtherClass();echo $otherClass->getWebsiteNameOfCmsInstance($CMS);

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...