Core PHP

A Simple Class

A class gives programmers a way of defining their own data types. With classes, the format of a user-defined data type is created. Once a class is defined, instances of the data type can be created, which are refereed to as objects. The process of creating instances of objects is called instantiation.

We have introduced some terminology which we will make concrete with a simple example class called CMan. Below, the file "CMan.php" defines the class or datatype CMan inside it and instantiates it once. The entire class consists of two data fields or members: msName and miAge. These two fields are used to define two aspects or properties of a "man," namely, the "name" and "age" of the man. I have added some letters to these items in the code, like "ms", which we will ignore for now.

In the code below the class, we instantiate a CMan object by using "new" and assign it to the variable named $qMan. Then we access the members, msName and miAge, via the arrow operator -> and assign them the values "Jesus" and 33. Finally, we use the arrow operator again to access the memebers and output them via the "echo" command.

CMan.php

<?php
  class CMan {
    var $msName;
    var $miAge;
  }

  $qMan = new CMan();

  $qMan->msName = "Jesus";
  $qMan->miAge = 33;

  echo "Name: " . $qMan->msName . "<br />";
  echo "Age: " . $qMan->miAge . "<br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.