Jump to content

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)

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.