Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Simple PHP class tutorial

Here is an example of simple PHP class and explanations of how things are done, what they mean and example usage. You should be familiar with programming basics to understand this.

In classes functions are called methods and variables are called properties.

<?php
//defining class name which will be used to create instance
class classname
{
    //private property can be used only inside class
    private $priv_var = "private property";
    
    //public property can be accessed through class instance
    public $pub_var = "";
    
    //to pass value to constructor, you need to pass it when creating instance
    //how ever this is optional, you may not define construct at all
    function __construct($var){
        //this is how properties and methods are used inside class
        $this->pub_var = $var;
    }
    
    //public method to set value to property that can't be accessed directly
    public function set_property($value){
        //using private method to do some checking
        if($this->check_value($value))
        {
            //setting value of private property
            $this->priv_var = $value;
        }
    }
    
    //public method to get value of private property
    public function get_property(){
        return $this->priv_var;
    }
    
    //property that can be used inside class only
    private function check_value($value){
        //just checking value
        if(trim($value) != "")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    function __destruct(){
    
    }
}

//example usage

//creating instance and passing value to constructor
$class = new classname("public property");

//geting pulic property value
$var = $class->pub_var;
echo "<p>".$var."</p>";

//getting value of private property through public method
$var = $class->get_property();
echo "<p>".$var."</p>";

//changing value of private property through public method
$class->set_property("private property can be changed like that");

//getting new value of private property
$var = $class->get_property();
echo "<p>".$var."</p>";


?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus