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
https://forums.phpfreaks.com/topic/77611-solved-elementary-php-question/
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).

 

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();
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.