简体   繁体   English

PHP常量在类内部设置,但是我现在需要在类外部进行更改,可以这样做吗?

[英]PHP constant set inside class, but I need to alter it outside the class now, can this be done?

I have a simple core class that is being used for core functions to a small web app. 我有一个简单的核心类,该类用于小型Web应用程序的核心功能。 I have defined some constants in the class - which has mostly static functions - and I am wanting to set / edit these constants outside of the class, example: 我在类中定义了一些常量-其中大多数具有静态函数-我想在类外设置/编辑这些常量,例如:

class core{
  const connection = '';
  public static function someSqlScript(){
    $sql = "SELECT * FROM sometable WHERE someconditions";
    $exec = mysqli_query(self::connection, $sql);  
  }
}

Now, I want to be able to set the connection constant so that it references a mysql connection object, which (by means of another script), has already been assigned to the variable $con, so essentially I am after something like this: 现在,我希望能够设置连接常量,以便它引用一个mysql连接对象,该对象(通过另一个脚本)已经分配给变量$ con,因此从本质上讲,我需要执行以下操作:

core::connection = $con; //send connection for use in class
core::someSqlScript(); //should not perform the MySQL query using conneciton $con as above

Any help is greatly appreciated, I am used to using non static functions and variables within classes, but the static functions with constants has got me. 非常感谢任何帮助,我习惯于在类中使用非静态函数和变量,但是带有常量的静态函数让我受益匪浅。

Thanks to all. 谢谢大家。

The meaning of constant is, that you can't change it. 常量的意思是,您不能更改它。 You want a static variable : 您需要一个静态变量

class core{
  public static $connection = '';
  public static function someSqlScript(){
    $sql = "SELECT * FROM sometable WHERE someconditions";
    $exec = mysqli_query(self::$connection, $sql);  
  }
}

core::$connection = $con; 
core::someSqlScript(); 

Note the public static $connection instead of const connection and self::$connection instead of self::connection (also core::$connection instead of core::connection ). 注意public static $connection而不是const connectionself::$connection而不是self::connection (也是core::$connection而不是core::connection )。

常量的概念是,定义后不能更改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM