Reputation: 323
Here's the class I am working on. After uploading a file using a form, it POSTS to this php file which contains this class:
class Parse
{
public $file;
public function __construct()
{
echo 'The class was initiated!<br />';
}
public function setFile($file)
{
if (sizeof($file) == 1)
{
$this->file = $file;
}
}
public function getFileName()
{
return $this->file['uploadedfile']['name'];
}
public function getFileTempName()
{
return $this->file['uploadedfile']['tmp_name'];
}
public function getFileSize()
{
return $this->file['uploadedfile']['size'];
}
}
Should I directly reference $obj->file['uploadedfile']['property'] like how I created the Getters, or should I create a bunch of public class properties like public $filename
and store the values from the $_FILES variable into individual class properties?
Which is best-practice?
EDITED WITH ANSWER
This code works perfectly:
<?php
class Parser
{
public $file;
public function __construct()
{
echo 'The class was initiated!<br />';
}
public function setFile($file)
{
if ($_POST) {
if ($file['uploadedfile']['size'] > 0) {
$this->file = $file;
} else {
echo "File not uploaded!<br />";
}
} else {
echo "The form was not submitted!<br />";
}
}
}
################
# test area
################
$obj = new LoLParser;
$obj->setFile($_FILES);
?>
Upvotes: 1
Views: 82
Reputation: 270609
Given that $_FILES
is a superglobal, available in all scopes, you don't really gain anything there are some particular small gains by storing it as a class property. There may be some benefit to holding it as a property for readability inside the class. As pointed out in comments, it also provides a path to mocking data for unit testing.
However, creating getter methods for $_FILES
seems to add needless complexity and confusion in my opinion. Getters are useful to expose private or protected properties outside the class, but serve little purpose when accessing a superglobal, since you cannot protect the contents of a superglobal anyway.
Upvotes: 1