We help IT Professionals succeed at work.
Get Started

PHP variables as objects

Last Modified: 2015-03-02
I'm not sure this is a question that's directly answerable but I thought I'd give it a try.

In some other languages variables are created as objects, allowing you to manipulate the value of the variable.

For example, in Objective-C (i believe) you can create a string like this (or similar);

my_name = [NSString]

Open in new window

Does anyone know if anyone has built a similar set of objects for PHP?

For example, I'd envisage it working as such;

$my_name = new pString()->set('John Doe');
$my_dob = new pDateTime()->set('07-08-1980');

echo $my_dob->get('Y-m-d'); // Notice how the get method can handle the formatting for you.

Open in new window

My main reason for asking is I use objects a lot in projects, and think being able to do something like the following would be useful (most of my objects are linked to database tables);

class car {

public $id;
public $make;
public $model;
public $registered_date;

public function __construct() {
$this->id = new pInt()->setLength(11)->autoIncrement(true)->primaryKey(true);
$this->make = new pString()->setLength(20);
$this->model = new pString()->setLength(15);


Open in new window

A simple object such as pString can then manipulate the string to 1) make sure it's a string, 2) strip it's length to match the length set when the pString object was created and so on. Because we know the variable is a pString object, it would be possible to have the object generate the SQL code required to create the car object in a mysql database, as it would know the type, length of the variable.

I've been thinking of creating something like this for my own projects, however I can't believe that this hasn't already been done and there's a collection of objects that can be added to your project to do just this already?

Does anyone know if such a library of objects exists?
Watch Question
Most Valuable Expert 2011
Author of the Year 2014
This problem has been solved!
Unlock 2 Answers and 4 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE