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?

9
  • 1
    possible duplicate of Setting POST variable without using form Commented Nov 17, 2014 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 ? Commented Nov 17, 2014 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)? Commented Nov 17, 2014 at 13:09
  • 1
    Leandro is correct the answer is in the link provided. Commented Nov 17, 2014 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. Commented Nov 17, 2014 at 13:18

1 Answer 1

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();
 ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I can't test my code now, so your example was very helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.