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
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');

Link to comment
Share on other sites

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.