Jump to content


Photo

PHP Access Function Outside of Class


  • Please log in to reply
1 reply to this topic

#1 Pooch

Pooch

    Young Padawan

  • Members
  • Pip
  • 63 posts

Posted 22 July 2006 - 11:03 AM

Hi,

I just switched from Procedural Programming to Object Oriented and I was wondering if there was a way to access a function outside of a class?

Example:
function dog($variable) {
 echo $variable . " Bark!";
}

class Cat {
 var $cat = dog("Meow); // this doesn't work ! ! !
/*
* If the function dog were in the class I'd access it by using:
* $this->dog("Meow");
* But Since it's out of the class, I am not sure how to use it.
*/
}


#2 rc69

rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 22 July 2006 - 12:28 PM

function dog($variable) {
	return $variable . " Bark!";
}

class Cat{
var $cat;
	function Cat(){
		$this->cat = dog("Meow");
		echo $this->cat;
	}
}
A function defined outside of the class can't be used as one of it's method's. Also, just like when defining function variables, when defining var's inside a class, it has to be set to a static value (no constants, functions, or other variables).

You're also missing an end quote after "Meow where you define $cat.

Check php.net for more info, they have OOP sections for both php 4 and 5.

Edited by rc69, 22 July 2006 - 12:29 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users