Core\Ast\Node::line
$node->line(): intThe line where this part of the source starts, counted from 1.
This is the number a person reads down the side of an editor, so a report that gives a file and a line is one they can jump straight to. Use column with it when you want the exact place along the line, and offset when you need the position in bytes.
The line is where the part starts. A class that runs from line 8 to line 30 has the line 8, and every method inside it has its own. To find where a part ends, take the largest line among its nodes.
Good to know: a newline inside a text value counts. Source that holds a value written over three lines puts the next statement three lines further down, which is what an editor shows.
The examples below show how to name the place of each part of a program, how many lines a class covers, and a check for lines holding more than one statement.
Return value
Returns int. The line of the node's first character, counting the file's first line as 1.
Examples
Naming the place of every part
<?nvs// Shows how to name the place of each part of a program. A report that gives a// file and a line is one an editor can jump straight to.
string $source = <<<'NVS'<?nvsint $count = 2;
echo $count, "\n";NVS;
// This prints orders.nvs:2, then orders.nvs:4.foreach (Core\Ast::parse($source)->children() as Core\Ast\Node $part) { echo 'orders.nvs:', $part->line(), "\n";}orders.nvs:2orders.nvs:4How many lines a class covers
<?nvs// Shows how to measure a class in lines. The class starts on its own line, and// the largest line below it is where its last statement sits. The closing// brace is not a part of the program, so it has no line of its own.
string $source = <<<'NVS'<?nvsclass Invoice { public static function total(int $a, int $b): int { return $a + $b; }}
class Receipt { public static function line(): string { return "one"; }}NVS;
// This prints lines 2 to 4, then lines 8 to 10.foreach (Core\Ast::parse($source)->children() as Core\Ast\Node $class) { int $first = $class->line(); int $last = $first; foreach ($class->nodes() as Core\Ast\Node $node) { if ($node->line() > $last) { $last = $node->line(); } } echo 'lines ', $first, ' to ', $last, "\n";}lines 2 to 4lines 8 to 10Finding lines that hold more than one statement
<?nvs// Shows how to find lines that hold more than one statement. Some teams ask// for one statement per line, because a line doing three things is harder to// read and harder to step through.
string $source = <<<'NVS'<?nvsint $a = 1; int $b = 2;echo $a + $b, "\n";NVS;
// The parts come in source order, so a part on the same line as the one before// it is a second statement on that line.int $previous = 0;
// This prints one report, for line 2.foreach (Core\Ast::parse($source)->children() as Core\Ast\Node $part) { if ($part->line() == $previous) { echo 'line ', $part->line(), " holds more than one statement\n"; } $previous = $part->line();}line 2 holds more than one statement