1

In my project, I had defined a Datasource class in php.

I want to call function with class, so I had define static getRedis function in Datasource class.

Here is Datasource.php code:

<?php

 namespace common;

 class Datasource {

 public $config_name;  

 public $server_region;  


public function __construct() {}

public static function getRedis($config_name = NULL, $server_region = 'default') {
    $this->config_name=$config_name;
    $this->server_region=$server_region
    return $this->config_name;
}
}

Now I want to call getRedis function and display instance1 in my html page;

Here is html code:

<?php 
include "o1ws1v/class/common/Datasource.php";

$redis_obj = common\Datasource::getRedis('instance1');
echo $redis_obj;
?>

But it words fail. I can not get $redis_obj. it shows nothing.

Who can help me?

2
  • You're missing a semicolon in your function. As Barmar wrote, you have to use self:: instead of $this Commented Jun 12, 2018 at 2:06
  • 1
    A static method doens't have a $this variable. Commented Jun 12, 2018 at 2:06

2 Answers 2

1

Problem is you are using $this context in static method. If you made your class variables static it will work.

More info Static keyword

Your code:

<?php

 namespace common;

 class Datasource {

    public static $config_name;  

    public static $server_region;  

    public static function getRedis($config_name = NULL, $server_region = 'default') {
        self::$config_name=$config_name;
        return self::$config_name;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are just trying to call a function from your class, it does not have to be static. Make you function in your class public and it does not need to be in a constructor.

This is in your class.

public function getRedis($config_name = NULL, $server_region = 'default') {
    $this->config_name=$config_name;
    $this->server_region=$server_region;
    return $this->config_name;
}

In the file that you want to call you function.

$variable = new Datasource; 
$variable->getRedis(); //This will call your function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.