PHP - Accessing Class Properties

Introduction

Once you've created a class property, you can access the corresponding object's property value from within your calling code by using the following syntax:

 
$object->property; 
 

The property name doesn't have a $ symbol before it.

Here's an example that shows how to define properties then set and read their values:

Demo

<?php 
 
     class Truck { 
        public $color; 
        public $manufacturer; 
     } /*from w  ww. j av a2  s  . co  m*/
 
     $myTruck = new Truck(); 
     $myTruck->color ="red"; 
     $myTruck->manufacturer ="Niu"; 
 
     $myTruck2 = new Truck(); 
     $myTruck2->color ="green"; 
     $myTruck2->manufacturer ="Ford"; 
 
     echo "The usa's color is". $myTruck->color.".\n"; 
     echo "The Mustang's manufacturer is". $myTruck2->manufacturer.".\n"; 
     echo "The \$myTruck Object: \n";
     print_r($myTruck); 
     echo "\n"; 
     echo "The \$myTruck2 Object: \n"; 
     print_r($myTruck2); 
?>

Result

Related Topic