开发者

PHP : how do i access a request variable outside of a class?

I have a form passing a variable $oid to a php script. the form variable is pulled and needs to be passed into a function called get_name(). The header() function in the class implements an interface called header() in the parent class.

    require 'pdfclass.php'; 
    $oid = $_REQUEST['oid']; 

    class p extends PDF { 
       function Header() { 
          $this->setF('Arial',10); 
          $this->Cell(50,10,get_name($oid),1,0,'c'); 

       } //end Header() 


    } //end class 

    function get_name($oid) {... } 

$pdf = new P(); 
$pdf->setF('Times',12); 
$pdf->AddPage(); 
$pdf->O开发者_运维问答utput(); 

When i run this, i get an error on the get_name($oid) call inside the class extension. I wish to avoid using a global variable. Any ideas how to do this?

thanks in advance


The obvious answer would be to pass the variable as an argument:

class p extends PDF { 
   function Header($oid) { 
      $this->setF('Arial',10); 
      $this->Cell(50,10,get_name($oid),1,0,'c'); 
   }
}

$p = new p();
$p->Header($oid);

If that's not possible for some reason, say because the function is called by something else, you can pass it to the constructor:

class p extends PDF { 

   public $oid = null;

   public function __construct($oid /*, $original, $arguments */) {
       $this->oid = $oid;
       parent::__construct(/* $original, $arguments */);
   }

   public function Header() { 
      $this->setF('Arial',10); 
      $this->Cell(50,10,get_name($this->oid),1,0,'c'); 
   }

}

$p = new p($oid /*, 'foo', 'bar' */);


Various ways to fix this, I'm gonna delve into how and why one is better. Simplest fix is:

   function Header($oid) { 
      $this->setF('Arial',10); 
      $this->Cell(50,10,get_name($oid),1,0,'c'); 
   } //end Header() 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜