$argv in a class
Asked Answered
S

2

8

I'm using exec() to exec a file but the file is in a class, I read more about argv but it was confusing. I need to get it to work inside a class.

It says:

Please note that, $argv and $argc need to be declared global, while trying to access within a class method

on php.net

Samekh answered 12/8, 2012 at 18:32 Comment(1)
And what the goal? Arguments are for console execution.Hermanhermann
L
27

That means argc/argv aren't superglobals - they're only visible at the top-level context of PHP scripts, so...

<?php

$x = $argv[1]; // works

class foo {
   function bar() {
       echo $argv[1]; // undefined
   }
   function baz() {
       global $argv;
       echo $argv[1]; // works
   }
}
Lucilla answered 12/8, 2012 at 18:35 Comment(1)
This can be done by using $GLOBALS['argv']... as well. In case copying a variable to your current scope or trying to make them superglobal is undesirable.Isaiah
A
0

i add argv as arguments to the class constructor

class MyClass
{
    protected $args;

    public function __construct($args) 
    {
        $this->args = $args;
    }

    public function foo()
    {
        $this->args[1]; //access args using $this->args
    }
}

$myClass = new MyClass($args);
Adverse answered 24/8, 2018 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.