1

This is my code. It is giving me an error. I am new in OOP in PHP, please help me regarding this particular issue.

Code as following:

<?php 
class myclass 
{
   var $name;
   //public $vari="this is my class ";
   public function setvalue($newval)
   {
       $this->$name=$newval;
   }
   public function getvalue()
   {
       return $this->name;

   }
}

$object= new myclaas;
$object->setvalue("usman");
echo $object->getvalue();
?>

Error as following:

Fatal error: Class 'myclaas' not found in E:\wamp\www\oops\myclass.php on line 19
0

2 Answers 2

2

These are the two errors in your code. You didn't type the class name properly when you instantiated the class.Your class name is myclass , But you typed the class name myclaas.

Your Code

 $object= new myclaas;

See the corrected line below.

 $object= new myclass;

When you access properties in a class using $this pseudo variable don't insert a dollar sign in front of the variable (In your code see the $ sign in $name , You don't need it).

Your code look like this

 $this->$name = $newval;

You need to change the code to

 $this->name = $newval;

Updated code

<?php 
class myclass 
{
   var $name;

   public function setvalue($newval)
   {
       $this->name=$newval;
   }
   public function getvalue()
   {
       return $this->name;

   }
}

$object= new myclass;
$object->setvalue("usman");
echo $object->getvalue();
?>

Thanks and Have a good one :)

Sign up to request clarification or add additional context in comments.

Comments

1

Final edit -

class myclass 
{
 var $name;

public function setvalue($newval)
{
   $this->name=$newval;      //variable calling was incorrect
}
public function getvalue()
{
   return $this->name;
}
}



$object= new myclass;    //class name correction
$object->setvalue("usman");
echo $object->getvalue();

2 Comments

thanks u and stackoverflow bidaway what was the issue
spelling mistake for class name and ( $this->name ) right way to access class variables not this ($this->$name). I hope my code is useful to be marked correct.

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.