Jump to content

An error i got whilst handling classes - php

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
totonex

totonex

    Learning Programmer

  • Members
  • PipPipPip
  • 82 posts
I got an undefined function error.

Here's how my code codes:
class MyClass()
{
 private $var;
  public function SetVarManually($somevar)
   {
    $this->var=$somevar;
   }
  private function IWillUseThisLater($symbol)
   {
    if($symbol=='*') return 1;
    if($symbol=='+') return 0;  
   }
  public function SetVarDifferently()
  {
   $this->var=strval(IWillUseThisLater('*'));
  }
}

$instance=new MyClass;
$instance->SetVarManually('random string'); // this works.
$instance->SetVarDifferently(); // this gives and undefined function error,
                                   //more precisely that IWillUseThisLater is undefined.


#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
$this->var=strval($this->IWillUseThisLater('*'));


#3
totonex

totonex

    Learning Programmer

  • Members
  • PipPipPip
  • 82 posts
I understood my error, but...

Ok, this was just the tip of the iceberg -
I have 2 public functions within my class, and this private one i tried to use wrongly in my example.

In both of the public functions , i call the IWillUseThisLater function as in my example ( without $this-> ) , yet in one of them i do not get the undefined error. Why?

#4
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
You have to either use $this-> or $self:: to access member functions of a class, unless the functions are nested.

<?php


class Foo {



	

	private function function_two()

	{

		echo "Function Two!";

	}


	public function function_one()

	{

		function function_two() {

			echo "Function One!";

		}

		

		function_two();

		$this->function_two();

	}

}



$foo = new Foo();

$foo->function_one();


?> 


#5
totonex

totonex

    Learning Programmer

  • Members
  • PipPipPip
  • 82 posts
Thanks John, just found out that the problem was elsewhere in my code, and yes, i should've used $this->method. So noow it works.
Thanks!