Calling PHP Class Function In My Page

2019-09-01 17:09发布

问题:

I have a class file: we'll call it class.php. The functionality of that is to grab info from an ini file (yeah, I posted the question about security and was given the great suggestion to use either a config file or an ini file to hold the DB information).

Essentially, my class is this:

<?php  
class myClass
{   
    public function getAttached()
    {
        $file = "../../myFile.ini";
        if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');

        $hoost = $settings['mysqli']['default_host'];
        $useer = $settings['mysqli']['default_user'];
        $pazz = $settings['mysqli']['default_pw'];
        $dbs = $settings['mysqli']['default_db'];

        $con = mysqli_connect($hoost ,$useer, $pazz, $dbs);

        return $con;
    }
}
    $obj = new myClass();
    $obj->getAttached();
    $vals = $obj->getAttached();
    //echo $vals;  //didn't know if I should echo this or not.
?>

I want to call this in my somePage.php file to make my "mysqli" connection and go from there...

I tried this:

require_once('class.php');
getAttached();

Obviously that didn't work (I knew it wouldn't but - I did it anyway just to see if "maybe"), so - how do I call that function from my class file in the regular php page?

Any thoughts would be appreciated. Thanks in advance.

回答1:

You need to make an instance of the class before calling the functions as they're not static.

require_once('class.php');
$myClass = new myClass();
$myClass-> getAttached();

or, like I said above you could make the function static.

public static function myFunction() {
    //etc...
}

Then to call it you would use:

require_once('class.php');
myClass::getAttached();


回答2:

You have to instanciate your class first, the same way you did it in you class.php file:

$myclass = new myClass();
$myClass->getAttached();

Note that if your method can be used without any relation with your class, you could make it static:

public static function getAttached() {
   // ...
}

And use it without having to instanciate your class:

myClass::getAttached();


回答3:

Your getAttached() method within the myClass ,create the instance for the class and call

the function

$call = new myClass();
$call->getAttached();


回答4:

Given answers are correct, but if you keep your class file as you posted, you have object already in $obj so there is no need to make new one. If it is just temporary you can ignore my post.

One more thing:

  $obj->getAttached(); // this line is not needed, as you call this function in next line
  $vals = $obj->getAttached();