Jump to content

Question about instantiate a class


lopes_andre

Recommended Posts

Hi,

 

I'm newbie to php opp.

 

I just need to know if it is possible to instantiate a class like this?

 


$import = new geoIpImportCSV(obtainDownloadFileName(), 'table1');

class geoIpImportCSV {

private $input_zip_file;
private $db_table;  

function __construct($input_zip_file, $db_table) {
	$this->input_zip_file = $input_zip_file;
	$this->db_table       = $db_table;
}

/*
"GeoLiteCity_" . $date . ".zip".
*/
function obtainDownloadFileName() {
	return "GeoLiteCity_20101201.zip";
}

    // ...
}

 

It is possible to call a method(obtainDownloadFileName()) like this to the constructor?

 

Best Regards,

 

Link to comment
https://forums.phpfreaks.com/topic/221994-question-about-instantiate-a-class/
Share on other sites

It IS possible to call a function as a parameter to another function call. HOWEVER, the function (as a parameter) has to resolve completely BEFORE the outer function is called. So the object will NOT exist when the (parameter) function is called. [by the way, the way you have it written obtainDownloadFileName() is a normal function call NOT a class or object method call]

 

You could pass the method name as a string and have the constructor call it:

class clsTryme {
  function __construct($funcToGetFile, $table) {
    $this->fileName = $this->$funcToGetFile();
    $this->table = $table;
  }

  function getGeoFile() {
    return 'geo_file.zip';
  }
} 

$obj = new clsTryme('getGeoFile', 'table1');

 

or just have the constructor call the method without passing it in:

class clsTryme {
  function __construct($table) {
    $this->fileName = $this->getGeoFile();
    $this->table = $table;
  }

  function getGeoFile() {
    return 'geo_file.zip';
  }
} 

$obj = new clsTryme('table1');

 

IF your getGeoFile() method is a STATIC method, then you can call it in the call to the constructor:

class clsTryme {
  function __construct($filename, $table) {
    $this->fileName = $filename;
    $this->table = $table;
  }

  static function getGeoFile() {
    return 'geo_file.zip';
  }
} 

$obj = new clsTryme(clsTryme::getGeoFile(), 'table1');

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.