Jump to content

From one class to another


utahcon

Recommended Posts

I have a script that I am writing and I ran into a snag with my debug, which if this is a real problem kind sucks for me...

 

I have two classes I am working with right now, Site and Debug.

 

In my code I call

 

$debug = new Debug;

 

and then later I call

 

$site = new Site;

 

Finally in the Site class I want to write to the debug variable debugText so I try: (this is in Site)

 

$debug->debugText .= 'My new text';

 

However nothing gets written to the variable

 

ideas? is it possible to do that?

Link to comment
https://forums.phpfreaks.com/topic/50362-from-one-class-to-another/
Share on other sites

what version of php are you using, i'm not sure that it matters much but i'm running 5 and the following works for me...

 

 


<?php

ini_set('error_reporting', 8191);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);


class Site{

  public function changetext($debug){

    $debug->debugText = 'My new text.';

  }

}


class Debug{

  public $debugText;

  public function talk(){

    echo $this->debugText;

  }

}


$debug = new Debug();

$site = new Site();


$site->changetext($debug);

$debug->talk();


?>

for that to work (site class changing debug's properties) you need to do one of a few things:

 

have site extend debug or the inverse

instantiate debug inside of the site class or the inverse, and pass the debug obj along as a property of site

or pass a reference to the debug class to the site class ie $x = new site(new debug()); or some variant

While I agree with the previous two posts, I'd like an offer up a different approach. 

 

I really dislike the idea of instantiating objects whose sole purpose is to echo or log something.  By doing this you are leaving a chunk of allocated memory sitting on the heap which is really not needed.  This deficiency will become more pronounced the larger the String is that you are trying to print.  I would suggest that you consider using a static class for your debugger.  This approach doesn't waste memory on the heap or require you to pass references to the debug instance all throughout your code.

 

If I may borrow Benjamin's code snippet:

 


<?php

ini_set('error_reporting', 8191);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

define('DEBUG_ON', true);

class Site
{

  public function changetext($debug)
  {

    Debug::out('My new text.');

  }

}


class Debug
{

  public static function out($str)
  {
    if(DEBUG_ON) echo $str;
  }

}

$site = new Site();
$site->changetext();

?>

 

Best,

 

Patrick

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.