Create a class with public fields in PHP

Description

The following code shows how to create a class with public fields.

Example


<?php//from  w w w .  j a  va 2  s  . c o m

class Car {
  public $color;
  public $manufacturer;
}

$beetle = new Car();
$beetle->color = "red";
$beetle->manufacturer = "Volkswagen";

$mustang = new Car();
$mustang->color = "green";
$mustang->manufacturer = "Ford";

echo "<h2>Some properties:</h2>";
echo "<p>The Beetle's color is " . $beetle->color . ".</p>";
echo "<p>The Mustang's manufacturer is " . $mustang->manufacturer . ".</p>";
echo "<h2>The \$beetle Object:</h2><pre>";
print_r( $beetle );
echo "</pre>";
echo "<h2>The \$mustang Object:</h2><pre>";
print_r( $mustang );
echo "</pre>";

?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition