Jump to content

public variables in php classes = $_GET['name']


iNealec

Recommended Posts

I am working with a php class which contains public variables like so:

 

public $var = "sometext";  <-- This works

 

But when I try to assign an $_GET['value'] to that variable, dreamweaver is saying there is a syntax error.

 

public $var = $_GET['value'];  <-- this doesn't work

 

Is there a way around this problem?


$createuserfile = $_GET['userID']."-file.txt";
echo $_GET['userID']; <-- This works, but the file created below gets named -file.txt
$ourFileHandle = fopen($createuserfile, 'w') or die("can't open file");
fclose($ourFileHandle);

$user = new Some_Class();

class Some_Class
{
public $userfile;

function __construct() {
$this->userfile = $_GET['userID']."-file.txt";
}

 

<?php
$createuserfile = $_GET['userID']."-file.txt";
echo $_GET['userID'];

$user = new Some_Class();

echo "<br/>";
echo "prop: ".$user->userfile;

class Some_Class
{
    public $userfile;

    function __construct() {
    $this->userfile = $_GET['userID']."-file.txt";
    }
}
And then if i go to script.php?userID=foobar, it outputs:

 

foobar
prop: foobar-file.txt
So there's something else going wrong in your code, wherever you are actually trying to use $this->userfile, that you're not showing.

A slight tweak to Some_Class (I'll rename it SomeClass):

class SomeClass
{
    public $userFile;
 
    public function __construct($file)
    {
        $this->userFile = $file;
    }
}
 
$myFile = new SomeClass($_GET['userID'] . "-file.txt");

I like it better that way because otherwise the class is dependent on $__GET['userID'] existing, which isn't good.

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.