PHP8に備えてPHP4形式の記述を修正する

検証用WordPressでデバッグを有効にしたらDeprecated(非推奨)が出力されていました。今のところ問題はないのですが将来的に困らないように修正しておきます。

DeprecatedはPHP4形式のコンストラクタで発生していた

こんな注意分がサイトのトップに表示されていました。

テキストだとこんな感じ。子テーマのfunctions.phpなので、自分で追加したコードに原因があるようです。45行目とあるのでこの後詳しく追ってみます。

Deprecated: Methods with the same name as their class will not be constructors in a future version of 
PHP; relative_URI has a deprecated constructor in /var/www/html/wp-content/themes/simplicity2-child/
functions.php on line 45

これを検索するとPHPの公式ドキュメントがヒットします。PHP7からPHP4形式で書かれたコードが非推奨となったようです。

■PHP 7.0.x で推奨されなくなる機能
http://php.net/manual/ja/migration70.deprecated.php#migration70.deprecated

該当コードを修正する

子テーマのfunctions.phpを調べてみると「WordPress内部生成URLの相対パス化」のコードでした。class名とfunctions名が一致しているのがダメとのこと。5年前の記事から更新されていないので仕方ないですね。

■[WordPress] すべてのURLを相対URLに置換する ( ただしOGP内の画像等は、置換しない)
https://gist.github.com/wokamoto/4633166

// Replace all URLs with relative URLs (don't replace images in OGP)
class relative_URI {
    function relative_URI() {
        add_action('get_header', array(&$this, 'get_header'), 1);
...
...
    }
}
new relative_URI();
コードをPHP5形式に修正する

ドキュメントによると対策は「__construct() メソッドを実装していれば、この警告は発生しません。」とのこと。つまりこういうことです。

// Replace all URLs with relative URLs (don't replace images in OGP)
class relative_URI {
-    function relative_URI() {
+    function __construct() {
        add_action('get_header', array(&$this, 'get_header'), 1);
...
...
}
- new relative_URI();
+ $relative_URI = new relative_URI();

ついでにインスタンス生成の記述も直しておきました。

対策の効果は?

当たり前ですがDeprecatedが表示されなくなりました。サイト表示が速くなったりだとか、メモリ消費が少なくなるとかの効果はありませんが、将来的な障害を回避できたと思えば気分もスッキリです。

スポンサーリンク