Jump to content

[SOLVED] Get a variable from a function


jackpf

Recommended Posts

Hi all,

Just wondering if it's possible to get a variable from within a function, something like this:

 

<?php
class blah
{
public $blah;
function blah()
{
	$this->blah = $this->blah2()->blah2;
}
function blah2
{
	$blah2 = 'this string should appear in the public var $blah';
}
}
?>

 

But it doesn't seem to work that way - $blah remains empy.

Any ideas on how to do this would be greatly appreciated,

Thanks,

Jack.

Link to comment
Share on other sites

Variables should be setup within a classes __construct, $blah2 is not a property of the blah2() method. Your code doesn't really make allot of sense.

 

<?php
class blah {
  public $blah;
  function __construct() {
    $this->blah = $this->blah2();
  }
  function blah2 {
    return 'this string should appear in the public var $blah';
  }
}

$blah = new blah;
echo $blah->blah;
?>

Link to comment
Share on other sites

I wouldn't want to post my entire code, as it's a super-cool syntax highlighter and someone might nick it :P

 

Basically , a simplified version is this:

 

<?php
class code
{
	function geshi($code)
	{
		$exist = array(
		'code to be highlighted',
		'more code'
		);
		$replace = array(
		'replacements',
		'more replacements'
		);

		return preg_replace($exist, $replace, $code);
	}
}
?>

 

And I wanted to extract the $exist and $replace arrays to use elsewhere. I took thorpe's advice and got round it by doing this, however:

 

<?php
class code
{
	var $exist, $replace;
	function code() // construct
	{
		$this->exist = array(
		'code to be highlighted',
		'more code'
		);
		$this->replace = array(
		'replacements',
		'more replacements'
		);

		//now I can access the $exist and $replace arrays upon calling the class
	}
	function geshi($code)
	{
		return preg_replace($this->exist, $this->replace, $code);
	}
}
?>

 

It doesn't look as neat, as the actual code is massive, but it works better.

 

So yeah, thanks for your help.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.