0

Is it possible to set $_POST data before calling another PHP method?

I'm trying to call a method from another PHP class. That method do not accept any arguments, it only takes $_POST data. So, my question is: is it possible to do something like this?

$_POST['name'] = 'John';

$user = new User();
$user->create();

The method "create" from the class "User" gets the $_POST['name'] data to create the record. Does it work?

  • 1
    possible duplicate of [Setting POST variable without using form](http://stackoverflow.com/questions/3418044/setting-post-variable-without-using-form) – Leandro Bardelli Nov 17 '14 at 13:06
  • 1
    Why you dont just try it ? I think it's work but really dont do this, $_POST is for post data, why dont use other variable ? – Benjamin Poignant Nov 17 '14 at 13:08
  • 1
    I would say this is a design flaw. What does `User` care where the name comes from and why don't you do `User::create($username, $password)`? – kero Nov 17 '14 at 13:09
  • 1
    Leandro is correct the answer is in the link provided. – Larry Lane Nov 17 '14 at 13:09
  • I saw the link Leandro sent before posting this one, but I thought that it's not exactly the same question because in that case the $_POST is being setted in the "next.php" file. In my case, I'm setting it outside the method, and outside the class, in another file. I'm setting it in another php file before calling the method. And the reason I'm trying to do this is because this is a method which is called by a form, but now we also have to create a batch file that will call it automatically, without any form data. I can't test it because it's not supposed to run now, only on weekends. – Danilo Teixeira Lopes Nov 17 '14 at 13:18
  • Do you redirect to or do you include the file with the create method? – Jens W Nov 17 '14 at 13:25
  • @JensW I'm using the require_once to use the methods from the class. Just for the record, the User->create thing is just an example to keep it simple, my real method is way more complex, and has nothing to do with user records. – Danilo Teixeira Lopes Nov 17 '14 at 13:31
  • Then it should work as described. But as kingkero noted, from a design perspective it's flawed, because of the dependency to the $_POST array inside of you method. – Jens W Nov 17 '14 at 13:39
  • Thank you all! I will consider changing the method to accept arguments. – Danilo Teixeira Lopes Nov 17 '14 at 13:52

1 Answers1

0

Yes, you can do like this.

Since $_POST is a superglobal associative array, you can change the values like a normal php array. Take a look at this piece of code. It will print "Hai".

<?php
 class first{
   public function index(){
     $_POST['text'] = 'Hai';
     $scnd = new second();
     $scnd->disp();
   }
 }
 class second{
   public function disp(){
     $cc = $_POST['text'];
     echo $cc;
   }
 }
 $in = new first();
 $in->index();
 ?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
RJ Anoop
  • 763
  • 13
  • 26