Fatal error: Using $this when not in object context in

Fatal error: Using $this when not in object context in


i want to use $this
because I am copy pasting it from other code
Who is Participating?
Greg AlexanderLead DeveloperCommented:
$this-> this is only available if you are in a class... you can start the class above that and set it to your own variable such as:

include "some_class.php";
$new_var = new some_class();

$new_var->name = name;

Open in new window

$this is only available in methods and not in functions. Eg. what works:

class A {
protected $name = 'foo';
public function inc() {
  include 'name.php';
  return $this;
public function out() {
  echo $this->name;

$x = new A();

$this->name = 'bar';
Ray PaseurCommented:
You might need to copy/paste a larger section of code, perhaps including all the class definition.
Mohamed AbowardaSoftware EngineerCommented:
If your code $this->name = 'name'; is NOT inside class, you must use the class name instead.

If you are using static variables you can use:
$className::name = 'name';

Open in new window

If you are using instance of the class, you can use:
$className->name = 'name';

Open in new window

To declare a class instance (change "YourClassName" with the name of your class):
$className = new YourClassName;

Open in new window

rgb192Author Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.