PHP: Properties and Methods

An Explanation on Properties and Methods in PHP.

1970 views

Edited: 2019-11-19 06:38

PHP article image

In object-oriented PHP Properties and Methods are just Variables and Functions found inside a class.

For some people the object oriented terms for functions and variables may seem rather confusing, so if you often get the terminology mixed up you could try thinking of methods as a specific way of doing something, as such it can only mean that the methods must refer to a function, since variables typically just sit there until something happens.

PHP Property Example

The below is a simple example of a class containing a few variables (Properties).

class MyClassName {
 public $Property1 = 'Hallo hallo!';
 public $MyVariableName = 'Hallo dude!'; // Another Property
}
$MyObject = new MyClassName();
echo $MyObject->Property1;
echo $MyObject->MyVariableName;

PHP Method Example

The below shows how to use functions (methods) inside of classes.

class MyClassName {
 public $AppVersion = 3;

 function VerCheck() {
     if($this->AppVersion < 3) {
         die("You need at least version 3 to run this script.");
     }
 }
}

$MyObject = new MyClassName();
$MyObject->AppVersion = 2; // Anything less then 3 would error out
$MyObject->VerCheck();

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials