簡體   English   中英

使用 PHP 在靜態方法中訪問 Class 屬性的最佳方法

[英]Best way to access Class property inside a Static method with PHP

這是我的班級財產

private $my_paths = array(
        'imagemagick' => 'E:\Server\_ImageOptimize\ImageMagick',
        'pngcrush' => 'E:\Server\_ImageOptimize\pngCrush\pngcrush.exe',
        'jpegtran' => 'E:\Server\_ImageOptimize\jpegtran\jpegtran.exe',
        'gifsicle' => 'E:\Server\_ImageOptimize\gifsicle\gifsicle.exe',
        'pngquant' => 'E:\Server\_ImageOptimize\pngquant\pngquant.exe',
        'pngout' => 'E:\Server\_ImageOptimize\pngout\pngout.exe'
);

同一個類中有一個靜態方法......

public static function is_image($file_path)
{

    $imagemagick = $this->my_paths['imagemagick']. '\identify';

    echo $imagemagick;
}

當然,這給了我這樣的錯誤

Fatal error: Using $this when not in object context...

然后我嘗試像這樣訪問屬性self::my_paths['imagemagick']但這沒有幫助。

我該如何處理?

您需要變量/屬性名稱前面的$符號,因此它變為:

self::$my_paths['imagemagick']

並且my_paths未聲明為靜態。 所以你需要它

private static $my_paths = array(...);

當它前面沒有static關鍵字時,它期望在對象中實例化。

您不能在靜態方法中訪問非靜態屬性,您應該在方法中創建對象的實例或將屬性聲明為靜態。

使其成為靜態屬性

   private static $my_paths = array(
    'imagemagick' => 'E:\Server\_ImageOptimize\ImageMagick',
    'pngcrush' => 'E:\Server\_ImageOptimize\pngCrush\pngcrush.exe',
    'jpegtran' => 'E:\Server\_ImageOptimize\jpegtran\jpegtran.exe',
    'gifsicle' => 'E:\Server\_ImageOptimize\gifsicle\gifsicle.exe',
    'pngquant' => 'E:\Server\_ImageOptimize\pngquant\pngquant.exe',
    'pngout' => 'E:\Server\_ImageOptimize\pngout\pngout.exe'
   );

並像這樣稱呼它

   self::$my_paths['pngcrush'];

一個類中的靜態方法不能訪問同一個類中的非靜態屬性。

因為靜態方法可以在沒有創建對象實例的情況下調用,所以偽變量$this在聲明為靜態的方法中不可用。

如果您不想訪問同一類的屬性,則必須將它們定義為靜態。

Example: 
class A{
    public function __construct(){
        echo "I am Constructor of Class A !!<br>";
    }

    public $testVar = "Testing variable of class A";

    static $myStaticVar = "Static variable of Class A ..!<br>";

    static function myStaticFunction(){

  //Following will generate an Fatal error: Uncaught Error: Using $this when not in object context 
      echo $this->testVar;

 //Correct way to access the variable..
    echo Self::$myStaticVar;

    }
}

$myObj = new A(); 
A::myStaticFunction();

如果可能,您也可以將變量 my_path 設為靜態。

self::my_paths['imagemagick']不起作用,因為數組是私有的,不能在靜態上下文中使用。

使您的變量靜態,它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM