WebRef.eu  - Internet Marketing and Online Business Resources  

Home / Site Map | Contact

 

How to Set a Variable Value within a PHP Class

The below script demonstrates how to set the value of a variable with a PHP class:

*** Example Starts ***

<?php
//PHP 5 example
//PHP class starts, we've put this class within the page but could have put it in a separate file

class MyClass {

//variable will be global inside the object
//the variable can be accessed both inside and outside of the class as we will see below

//class variables are also known as properties
//In PHP v5 we use public, protected or private to declare a variable, depending on its visibility
//We use public for the variable to be accessible from outside the class


public $MyClassVariable;


public function setMyClassVariable( $value )
{
$this->MyClassVariable = $value;
}

public function getMyClassVariable()

{
return $this->MyClassVariable;
}


}
//PHP class ends

//create an instance of the class as the $MyObject object
$MyObject = new MyClass();

//You access a class variable from outside the class using the arrow operator. The arrow tells php that the variable is part of the $mine object
$MyObject->setMyClassVariable("10");

echo $MyObject->getMyClassVariable();
?>

*** Example Ends ***

The browser output of this script should be 10.

 

 

 

 




Low Prices UK Shopping

Compare Prices
at LowPrices.co.uk


Home / Site Map | Contact

All Content ©2020 WebRef.eu