Jump to content

[SOLVED] Elementary PHP question


akufen

Recommended Posts

Hi all!

 

I get a 'Fatal error: Cannot access empty property' message when I try to print out the value of the $id field

of the returned $someObject. The odd thing is that the $id field is populated when I try to echo the value in the method which returns $someObject!

 

class someClass  {

public somefunction

{

  $someObject = new SomeObject;

  while ($stmt->fetch()) { $someObject->$id = $id; }

  $stmt->close();

 

  echo (someObject->$id); //This works!

  return $someObject;

}

}

 

$clazz = new SomeClass;

$someObject = $clazz->somefunction();

$echo someObject->$id; //This doesn't work!

 

Thanks in advance!

Link to comment
Share on other sites

So this is how you do it...

 

<?php

class myCar {

  var $color = "silver";

  var $make = "Mazda";

  var $model = "Protege5";

}

  $car = new myCar();

  $car -> color = "red";

  $car -> make = "Porsche";

  $car -> model = "Boxter";

  echo "I drive a: ".$car -> color." ".$car -> make." ".$car -> model;

?>

 

My mistake was that I was using something like $car -> $color = 'some color';

when the correct way to assign a field value to an object is $car -> color 'some color'; (with the $ removed from the field name).

 

Link to comment
Share on other sites

Just to throw some fuel to the fire, $car->$var is actually allowable, too, but it's the value of $var that gets parsed as the variable name. Check this out:

<?php
class myCar {
  var $color;
  var $make;
  var $model;

  function myCar($color = '', $make = '', $model = '')
  {
    $this->color = $color;
    $this->make = $make;
    $this->model = $model;
  }

  function getMake()
  {
    return $this->make;
  }
}

$car = new myCar('silver', 'Mazda', 'Protege 5');

$func = 'getMake';
echo $car->$func();
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.