Nasıl bir sınıfta bir dosya ekleyebilirim?

4 Cevap

Ben bir PHP sınıfı içinde herhangi bir yöntem / işlevi erişilebilir olması için bir dosya eklemek istiyorum. Dosya sadece bir base-64 kodlu değişkeni içerir. Bunu nasıl yaparsınız?

Teşekkürler.

4 Cevap

Bu durum için, daha iyi bir sabit kullanmak istiyorum.

define('MY_BASE64_VAR', base64_encode('foo'));

Bu her yerde ve değişmez sunulacak.

require "constant.php";
class Bar {
    function showVariable() {echo MY_BASE64_VAR;}
}

Tabii ki, yine de sınıfların kullanmadan önce tanımlanan dosyasını dahil etmek gerekir.

<?php include("common.php"); ?>

Giriş here.

Eğer her sınıfa dahil olduğundan emin olmak istiyorsanız, emin her sınıfta bunu eklemek yapmak ancak tasarrufuna yönelik include_onceyi kullanın

<?php include_once("common.php"); ?>

Sadece o dosyanın içinde base64 herhangi bir ek php kodu olmadan kodlanmış verileri kaydetmek, eğer sadece içeriğini okumak verilerin kodunu ve nesnenin bir özelliğine atayabilirsiniz.

class Foo {
  protected $x;

  public function setSource($path) {
    // todo: add as much validating/sanitizing code as needed
    $c = file_get_contents($path);
    $this->x = base64_decode($c);
  }

  public function bar() {
    echo 'x=', $this->x;
  }
}

// this will create/overwrite the file test.stackoverflow.txt, which isn't removed at the end of the script.
file_put_contents('test.stackoverflow.txt', base64_encode('mary had a little lamb'));
$foo = new Foo;
$foo->setSource('test.stackoverflow.txt');
$foo->bar();

baskılar x=mary had a little lamb.

(Bunu biraz daha ayrışmaya isteyebilirsiniz ... ama bu sadece bir örnek.)