An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ PHP functions ’

So you have successfully created a PHP class and want access to the classes variables and functions. As a reminder to programming beginners, you can only access public variables and public functions. That is a function or variable that was declared with the public keyword or no keyword (as PHP functions and variables are by default public). Below is a quick refresher example where functionNumberOne and functionNumberTwo are public and functionNumberThree is private.

class Common {
   public $secondVariable = "2";
   private $thirdVariable = "3";

   function functionNumberOne() {
      echo "This is my first function";
   }

   public function functionNumberTwo() {
      echo "This is my second function";
   }

   private function functionNumberThree() {
      echo "This is my third function";
   }
}

If the class is declared in another a separate file, remember to first include the file before your first attempt to access the class. Generally, the best place to include files is at the very top of the file.

Assuming our Common class function above, our first step to accessing our PHP variables and functions is to create an object. In programming terms, this is known as initializing an object instance. To create the class instance:

$myInstance = new Common();

How was the previous code snippet generated? You can choose any name to replace the $myInstance variable (so long as it is not a keyword). Next, new is a PHP keyword that in this situation signifies the creation of a new object. Finally, Common() is constructed by using the class name (in this case Common) followed by an open parenthesis and close parenthesis ‘()‘. If you have a specified a constructor, make sure you include the correct number of parameters.

Finally, to access the public variables we use the $myInstance object followed by ‘->’ and the public variable or function name. When accessing the variable name, you do not need to start with $. Again, we have a code example below.

echo $myInstance->secondVariable;
$myInstance->functionNumberOne();
$myInstance->functionNumberTwo();

And there we have it. You now have access to public PHP functions and PHP variables. Note that the use of classes is a new feature to PHP 5.