tags:

views:

19

answers:

2

in PHP 5 it would be

class Example {   
  private $foo = "old data";
  public function __construct(){}
  public function setVar($data){
      $this->foo = $data;
  }
  public function output(){
    return $this->foo;
  }
}
$var = new Example();
$var->setVar("new data");
echo $var->output();

I never learned OO in PHP 4 and am having trouble finding where to do this. Working with a class that I have to extend a bit. Any searches on this shows me a ton of ways to do this in PHP5 but not 4

Thanks

+1  A: 

To make this code PHP 4 compatible, you'd have to

  • remove the private public protected keywords

  • change private $foo = to var $foo =

  • change __construct() into Example() (the constructor is a method named after the class name)

but much more importantly, why do you need this? PHP 4's time is over. Except for historical purposes, there should be no need for new PHP 4 code any more. If you have a web host still running PHP 4, leave 'em.

Pekka
+1: Those are the exact changes necessary. And you do add an important fact: that one should just use php 5. Really, even when a client request php 4, strongly urge them to upgrade to php 5. php 4 is the past and developing specifically for it only creates troubles for later.
Jasper
guys you are both right. I'm using fpdf though, and it is still in PHP4. :(
Rick Weston
@Rick I think fpdf is just only using the old syntax to be backwards compatible with PHP4. If you are running PHP5 already and do not care about being compatible with PHP4, you can just as well use regular PHP5 syntax.
Gordon
@Gordon thanks, just discovered that as well. Now using PHP5 syntax
Rick Weston
A: 

See PHP Manual on Classes and Objects in PHP4 and Migrating from PHP 4 to PHP 5.0.x

class Example
{
  var $foo = "old data";

  function Example() {}

  function setVar($data){
      $this->foo = $data;
  }

  function output(){
    return $this->foo;
  }
}

$var = new Example();
$var->setVar("new data");
echo $var->output();
Gordon
Perfect, thank you!
Rick Weston