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

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


$this->name='name';

i want to use $this
because I am copy pasting it from other code
LVL 1
rgb192Asked:
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

0
 
hernst42Commented:
$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();
$x->inc()->out();

name.php
<?php
$this->name = 'bar';
0
 
Ray PaseurCommented:
You might need to copy/paste a larger section of code, perhaps including all the class definition.
0
 
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

0
 
rgb192Author Commented:
thanks
0
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.