Jump to content

[SOLVED] Variable scope


iarp

Recommended Posts

I'm having trouble with variables and accessing them within classes.

 

I have $L['base'] = '/home/'; at the start of my script and i need to access it within a class i've built a bit furthur down the page.

 

Parse error: parse error, expecting 'T_FUNCTION' in <LOCATION> on line 3

 

Line 3 pertains to

 

<?php

class systemsettings {

global $L;

...etc

 

 

etc...

}

?>

Link to comment
https://forums.phpfreaks.com/topic/153778-solved-variable-scope/
Share on other sites

You access class variables (outside the method) trough the use of $this->

 

Take this as an example

<?php
class MyClass
{
  private $name;

  function __construct( $pName )
  {
     $this->name = $pName;
  }
}
?>

notice how the dollar sign 'moves' to the front of $this->.

 

Think that should be of help?

The logical way to go about this would be by passing the variable as a parameter like this:

 

<?php
class systemsettings {
    function base( $pL ) {
         return  $pL['base'];
    }
}

$sysSettings = new systemsettings();
echo $sysSettings->base( $L );
?>

 

Or by passing it to the construct like this:

<?php
class systemsettings
{
  private $L;

  function __construct( $pL )
  {
     $this->L = $pL;
  }

  function base( $pL ) 
  {
     return  $this->L['base'];
  }
}

$sysSettings = new systemsettings( $L );
echo $sysSettings->base();
?>

 

Where the second example has the advantage that you could add another method doing something else with L['base'].. you gotta figure that one out for yourself which is the best to use for the given situation.

 

[edit]

A third (not recommended way) would be:

<?php
class systemsettings
{
  public $L;

  function __construct( $pL )
  {
     $this->L = $pL;
  }
}

$sysSettings = new systemsettings( $L );
echo $sysSettings->L;
?>

(class variable is public instead of private making it externally accessible)

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.