Reputation: 1078
I started learning oop php and I don't understand how to make a method inside a class execute. This is the code:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct(){
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query(){
var_dump($this->argList);
echo "haha";
}
gen_query();
}
new GrabData("apt_data_aptname");
Now, the __construct
function runs when I make a new GrabData object, but the gen_query
function doesnt execute. How do I make it execute it ?
Upvotes: 1
Views: 178
Reputation: 34837
If you always want to have the gen_query
function run when the class is initiated, you could link to it in the bottom of your constructor, like so:
function __construct() {
// Do your stuff here and then...
$this->gen_query();
}
Upvotes: 2
Reputation: 2493
A different way to run a class function without initiating the class is to use the double colon scope resolution operator, strangely called "Paamayim Nekudotayim".
GrabData::gen_query();
You can read up on it here.
Upvotes: 0
Reputation: 26861
First, you assign the object returned by the new
operator to a variable - then use that variable to execute methods on your object:
class GrabData {
public $tables=array();
public $columns=array();
public $argList;
function __construct() {
$this->argList=func_get_args();
$pattern;
var_dump($this->argList);
if(!empty($this->argList)){
foreach($this->argList as $value){
if(preg_match("/.+_data/",$value,$matches)){
if(!in_array($matches[0],$this->tables)){
array_push($this->tables,$matches[0]);
var_dump($this->tables);
}
$pattern="/". $matches[0] . "_" . "/";
array_push($this->columns,preg_replace($pattern,"",$value));
var_dump($this->columns);
}
}
}
}
public function gen_query() {
var_dump($this->argList);
echo "haha";
}
}
$super_object = new GrabData("apt_data_aptname");
$super_object->gen_query();
Upvotes: 1