PHP call Class method / function

2019-01-23 16:05发布

How can I call following Class method or function?

Let say I have this params get from url:

$var = filter($_GET['params']);

Class:

class Functions{

    public function filter($data){
        $data = trim(htmlentities(strip_tags($data)));

        if(get_magic_quotes_gpc())
            $data = stripslashes($data);

        $data = mysql_real_escape_string($data);

        return $data;
    }

}

thanks.

7条回答
我只想做你的唯一
2楼-- · 2019-01-23 16:47

This way:

 $instance = new Functions(); // create an instance (object) of functions class
 $instance->filter($data); // now call it
查看更多
孤傲高冷的网名
3楼-- · 2019-01-23 16:49

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);
查看更多
虎瘦雄心在
4楼-- · 2019-01-23 16:56

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);
查看更多
Deceive 欺骗
5楼-- · 2019-01-23 16:58
$f = new Functions;
$var = $f->filter($_GET['params']);

Have a look at the PHP manual section on Object Oriented programming

查看更多
在下西门庆
6楼-- · 2019-01-23 16:58

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

查看更多
手持菜刀,她持情操
7楼-- · 2019-01-23 17:09

Within the class you can call function by using :

 $this->filter();

Outside of the class

you have to create an object of a class

 ex: $obj = new Functions();

     $obj->filter($param);    

for more about OOPs in php

this example:

class test {
 public function newTest(){
      $this->bigTest();// we don't need to create an object we can call simply using $this
      $this->smallTest();
 }

 private function bigTest(){
      //Big Test Here
 }

 private function smallTest(){
      //Small Test Here
 }

 public function scoreTest(){
      //Scoring code here;
 }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();

hope it will help!

查看更多
登录 后发表回答